[英]In Django, how to get all instances of a model where an instance of another model related to the first by fk does not exist?
This is really tricky to me. 这对我来说真的很棘手。 I have the following models:
我有以下型号:
class Item(models.Model):
title = models.CharField(max_length=150)
item_type = models.CharField(choices=item_choices)
class Suggestion(models.Model):
user = models.ForeignKey(User)
item = models.ForeignKey(Item)
I need to get all the items of a given item_type that don't have a suggestion related to it and to a given user. 我需要获取给定item_type的所有与它以及给定用户没有建议的项目。 Can this be achieved in one query?
可以在一个查询中实现吗?
Many thanks! 非常感谢!
This can be done with .exclude()
: 这可以通过
.exclude()
:
items = Item.objects.filter(item_type=item_type).exclude(suggestion__user=user)
This follows the backwards relation to Suggestion
, and the forward relation to User
, and excludes any Item
s where the related user matches the given user. 这是继向后有关
Suggestion
,并正向关系到User
,并排除任何Item
在相关用户的用户符合秒。
One approach is to create a queryset of items with suggestions related to the user, then use that as a subquery. 一种方法是创建带有与用户相关建议的项目查询集,然后将其用作子查询。
items_suggested_by_user = Item.objects.filter(suggestion__user=user)
item_types = Item.objects.filter(item_type=item_type)
items = item_types.exclude(item__in=items_suggested_by_user)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.