我有两个具有一对多关系的模型 - parent 和 child 。我想查询所有没有 child 的 parent 。在 SQL 中,我会做这样的事情:
SELECT p.*
FROM parent p
LEFT JOIN children c on (p.id=c.parent_id)
WHERE c.id IS NULL
如何对单个 Django 查询执行相同的操作?
该模型的相关部分是:
class Parent(model):
...
class Child(model):
parent = ForeignKey(Parent, related_name='children')
最佳答案
使用 isnull
字段查找,其中:
Takes either True or False, which correspond to SQL queries of IS NULL and IS NOT NULL, respectively.
因此,查询集将如下所示:
Parent.objects.filter(children__isnull=True)
关于Django 查询空的related_set,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35389895/