Django 多对多过滤器() [英] Django ManyToMany filter()
本文介绍了Django 多对多过滤器()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个模型:
class Zone(models.Model):
name = models.CharField(max_length=128)
users = models.ManyToManyField(User, related_name='zones', null=True, blank=True)
我需要按照以下方式构建过滤器:
And I need to contruct a filter along the lines of:
u = User.objects.filter(...zones contains a particular zone...)
它必须是用户的过滤器,并且必须是单个过滤器参数.这样做的原因是我正在构建一个 URL 查询字符串来过滤管理员用户更改列表:http://myserver/admin/auth/user/?zones=3
It has to be a filter on User and it has to be a single filter parameter. The reason for this is that I am constructing a URL querystring to filter the admin user changelist: http://myserver/admin/auth/user/?zones=3
看起来应该很简单,但我的大脑不合作!
It seems like it should be simple but my brain isn't cooperating!
推荐答案
只是重申 Tomasz 所说的.
Just restating what Tomasz said.
There are many examples of FOO__in=...
style filters in the many-to-many and many-to-one tests. Here is syntax for your specific problem:
users_in_1zone = User.objects.filter(zones__id=<id1>)
# same thing but using in
users_in_1zone = User.objects.filter(zones__in=[<id1>])
# filtering on a few zones, by id
users_in_zones = User.objects.filter(zones__in=[<id1>, <id2>, <id3>])
# and by zone object (object gets converted to pk under the covers)
users_in_zones = User.objects.filter(zones__in=[zone1, zone2, zone3])
在使用 查询集.
这篇关于Django 多对多过滤器()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文