[英]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:
在 SQL 我会做这样的事情:
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?如何对单个 Django 查询执行相同的操作?
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: 使用
isnull
字段查找,该查找:
Takes either True or False , which correspond to SQL queries of IS NULL and IS NOT NULL , respectively.
接受True或False ,分别对应于IS NULL和IS NOT NULL的 SQL查询。
Thus, the queryset will look like the following: 因此,查询集将如下所示:
Parent.objects.filter(children__isnull=True)
menus = Menu.objects.filter(parent__name__isnull=True)菜单 = Menu.objects.filter(parent__name__isnull=True)
{% for menu in menus %} {% 用于菜单中的菜单 %}
{% if menu.childs.count > 0 %} ... {% if menu.childs.count > 0 %} ...
{% endif %} {% 万一 %}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.