问题
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