如何在django manytomanyfield上应用过滤器,以使该场遵循该条件的多个值?
class Publication(models.Model):
title = models.CharField(max_length=30)
class Article(models.Model):
headline = models.CharField(max_length=100)
publications = models.ManyToManyField(Publication)
p1 = Publication.objects.create(title='The Python Journal')
p2 = Publication.objects.create(title='Science News')
p3 = Publication.objects.create(title='Science Weekly')
我想过滤文章,并在p1
和p3
上发表。他们可能会或可能不会在其他出版物中发布,但必须在p1
和p3
中发布。
我尝试过:
Article.objects.filter(Q(publications=p1) & Q(publications=p3))
但是它返回空的queryset,这是不正确的
class Publication(models.Model):
title = models.CharField(max_length=30)
class Article(models.Model):
headline = models.CharField(max_length=100)
publications = models.ManyToManyField(Publication)
p1 = Publication.objects.create(title='The Python Journal')
p2 = Publication.objects.create(title='Science News')
p3 = Publication.objects.create(title='Science Weekly')
I want to filter articles, published in both p1
and p3
. They might or might not publish in other publications but they must have to publish in p1
and p3
.
I have tried:
Article.objects.filter(Q(publications=p1) & Q(publications=p3))
but it returns empty queryset which is not true
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果将mutliple链接到
filter()
他们的行为应该像与和
相连的行为:If you chain mutliple calls to
filter()
they should behave like being connected with anAND
:在多对多和一对一的测试中,有许多
foo__in = ...
样式过滤器的示例。这是针对您特定问题的语法:icontains
用于i
的case-costemintimentsmitive,包含
该单词包含这些字母,也许还有较少或更多字母。使用 noreflow noreferrer“> querySet) 。
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:The
icontains
used toi
for case-insensitive,contains
for that the word contains those letters and maybe there are fewer or more letters.The double underscore (__) syntax is used all over the place when working with queryset.
我遇到了一个类似的问题,有些用户以自由角色和付费角色结尾,因此我需要选择在许多领域中具有两个特定角色的用户。
我做了这样的事情,就像魅力一样
I had a similar problem where some users ended with a free role and also a paid role, so I needed to select users that have two specific roles on the many to many field.
I did something like this, works like a charm