我有两个这样的模型:
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.
更多推荐
发布评论