在Django QuerySet中,如何以多对一关系筛选“不存在”(In a Django QuerySet, how to filter for “not exists” in a many

编程入门 行业动态 更新时间:2024-10-26 08:28:58
在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)

实际上,每个模型都有更多的领域对这个问题无关紧要。

我想过滤所有以'a'开头并且没有报告的电子邮件的用户。 基于其他字段会有更多的.filter()和.exclude()条件。

我想要像这样来处理它:

users = User.objects.filter(email__like = 'a%') users = users.filter(<other filters>) users = ???

我想要 ??? 过滤掉没有关联报告的用户。 我将如何做到这一点? 如果这是不可能的,我已经介绍过了,什么是替代方法?

I have two models like this:

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.

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.

I want to approach it like this:

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()来防止重复结果。

Use isnull.

users_without_reports = User.objects.filter(report__isnull=True) users_with_reports = User.objects.filter(report__isnull=False).distinct()

When you use isnull=False, the distinct() is required to prevent duplicate results.

更多推荐

本文发布于:2023-08-02 19:34:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1379693.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不存在   关系   QuerySet   Django   filter

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!