简体   繁体   中英

Django query on empty related_set

I have two models with a 1-to-Many relationship - parent and child. I want to query all parents with no children. In SQL I would do something like this:

SELECT p.*
    FROM parent p
    LEFT JOIN children c on (p.id=c.parent_id)
WHERE c.id IS NULL

How can I do the same with a single Django query?

The relevant parts of the model are:

class Parent(model):
    ...

class Child(model):
    parent = ForeignKey(Parent, related_name='children')

Use the isnull field lookup, which:

Takes either True or False , which correspond to SQL queries of IS NULL and IS NOT NULL , respectively.

Thus, the queryset will look like the following:

Parent.objects.filter(children__isnull=True)

menus = Menu.objects.filter(parent__name__isnull=True)

{% for menu in menus %}

{% if menu.childs.count > 0 %} ...

{% endif %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM