Django: Filter a model with multiple parameters for a single ManyToManyField

爷,独闯天下 提交于 2019-12-14 02:41:25

问题


I have following models.

class Contents (models.Model):
  ...
  tags = models.ManyToManyField('Tag')

class Tag (models.Model):
  ...
  name = models.CharField(max_length=20)

Just to consider, I am trying to get contents which are tagged with both tag1 and tag2.

Is there a way in Django to do something like Contents.objects.filter(tags__name = ['tag1','tag2'])

Here tag1,tag2,... are dynamically generated.

Update:

I have been using for loop. I am looking for an efficient solution.


回答1:


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

See the docs.

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)

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



来源:https://stackoverflow.com/questions/22474310/django-filter-a-model-with-multiple-parameters-for-a-single-manytomanyfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!