Django ManyToMany过滤器() [英] Django ManyToMany filter()

查看:121
本文介绍了Django ManyToMany过滤器()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型:

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!

推荐答案

有很多例子是 FOO__in = ... 样式过滤器 many-to-many and 多对一测试。以下是您的特定问题的语法:

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])

双下划线使用查询结果时,会使用__)语法。

The double underscore (__) syntax is used all over the place when working with querysets.

这篇关于Django ManyToMany过滤器()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆