简体   繁体   English

具有多个约束的相关字段上的Django查询集

[英]Django queryset on related field with multiple constraints

Suppose I have the following models: 假设我有以下型号:

class User(models.Model):
    # ... some fields

class Tag(models.Model):
    # ... some fields

class UserTag(models.Model):
    user = models.ForeignKey(User, related_name='tags')
    tag = models.ForeignKey(Tag, related_name='users')
    date_removed = models.DateTimeField(null=True, blank=True)

Now I lets say I want to get all the users that have a given tag that has not yet been removed (ie date_removed=None). 现在我想说我希望得到所有尚未删除的给定标记的用户(即date_removed = None)。 If I didn't have to worry about the date_removed constraint, I could do: 如果我不必担心date_removed约束,我可以这样做:

User.objects.filter(tags__tag=given_tag)

But I want to get all users who have that given tag and have the tag without a date_removed on it. 但我希望获得具有该给定标记的所有用户并且标记上没有date_removed。 Is there an easy way in Django to get that in a single queryset? Django有一个简单的方法可以在单个查询集中获取它吗? And assume I have millions of Users, so getting any sort of list of User IDs and keeping it in memory is not practical. 并且假设我有数百万用户,因此获取任何类型的用户ID列表并将其保留在内存中是不切实际的。

Your filter() call can include multiple constraints: 您的filter()调用可以包含多个约束:

User.objects.filter(tags__tag=given_tag, tags__date_removed=None)

When they match, they will both match to the same Tag , not two possibly different ones. 当它们匹配时,它们将匹配相同的 Tag ,而不是两个可能不同的Tag

See the documentation on spanning multi-valued relationships; 请参阅跨越多值关系的文档 ; in particular, the difference between filter(a, b) and filter(a).filter(b) . 特别是, filter(a, b)filter(a).filter(b)之间的差异。 filter(a, b) filter(a).filter(b)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM