Django:为单个ManyToManyField过滤具有多个参数的模型 [英] Django: Filter a model with multiple parameters for a single ManyToManyField
问题描述
我有以下型号.
class Contents (models.Model):
...
tags = models.ManyToManyField('Tag')
class Tag (models.Model):
...
name = models.CharField(max_length=20)
请考虑一下,我正在尝试获取同时被两个tag1 and tag2
标记的内容.
Just to consider, I am trying to get contents which are tagged with both tag1 and tag2
.
Django中是否有一种方法可以执行Contents.objects.filter(tags__name = ['tag1','tag2'])
Is there a way in Django to do something like Contents.objects.filter(tags__name = ['tag1','tag2'])
此处tag1,tag2,...
是动态生成的.
更新:
我一直在使用for loop
.我正在寻找有效的解决方案.
I have been using for loop
. I am looking for an efficient solution.
推荐答案
如果要查找列表,则应该可以使用查找__in
:
If you're looking for a list, then you should be able to use the look up __in
:
Contents.objects.filter(tags__name__in = ['tag1','tag2'])
请参见文档.
对于同时具有两个标签和仅具有两个标签的查询集,您可能需要链接过滤器调用:
For a queryset with both and only both tags, you may need to chain your filter calls:
tags = ['tag1','tag2']
contents = Contents.objects.all()
for tag in tags:
contents = contents.filter(tags__name = tag)
这应该过滤查询集,以便您只有两个标签都匹配的查询集.从以下问题复制的方法: Django查询集以匹配所有相关对象
That should filter the queryset so that you only have a queryset where both tags match. The method copied from this quesiton: Django queryset to match all related objects
这篇关于Django:为单个ManyToManyField过滤具有多个参数的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!