在Django QuerySet中,如何过滤“不存在”以多对一的关系 [英] In a Django QuerySet, how to filter for "not exists" in a many-to-one relationship

查看:159
本文介绍了在Django QuerySet中,如何过滤“不存在”以多对一的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个这样的模型:

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?

推荐答案

使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆