在 Django QuerySet 中,如何过滤“不存在"?在多对一的关系中 [英] In a Django QuerySet, how to filter for "not exists" in a many-to-one relationship
问题描述
我有两个这样的模型:
class User(models.Model):
email = models.EmailField()
class Report(models.Model):
user = models.ForeignKey(User)
实际上,每个模型都有更多的字段,这些字段与这个问题无关.
In reality each model has more fields which are of no consequence to this question.
我想过滤所有拥有以a"开头且没有报告的电子邮件的用户.将有更多基于其他字段的 .filter()
和 .exclude()
条件.
I want to filter all users who have an email which starts with 'a' and have no reports. There will be more .filter()
and .exclude()
criteria based on other fields.
我想这样处理:
users = User.objects.filter(email__like = 'a%')
users = users.filter(<other filters>)
users = ???
我想要???过滤掉没有关联报告的用户.我该怎么做?如果这不可能如我所介绍的那样,有什么替代方法?
I would like ??? to filter out users who do not have reports associated with them. How would I do this? If this is not possible as I have presented it, what is an alternate approach?
推荐答案
注意:这个答案是在 2013 年为 Django 1.5 编写的.有关适用于较新版本 Django 的更好方法,请参阅其他答案
使用 isnull
.
users_without_reports = User.objects.filter(report__isnull=True)
users_with_reports = User.objects.filter(report__isnull=False).distinct()
当您使用 isnull=False
时,需要 distinct()
以防止重复结果.
When you use isnull=False
, the distinct()
is required to prevent duplicate results.
这篇关于在 Django QuerySet 中,如何过滤“不存在"?在多对一的关系中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!