I'm querying a ManyToMany field (tags). The values come from a list:
tag_q = Q()
tag_list = ["work", "friends"]
for tag in tag_list:
tag_q &= Q(tags__tag=tag)
Post.objects.filter(tag_q)
When I have only one value, it works flawlessly, but when more objects are stacked it always return an empty queryset.
I didn't used tags__tag__in=tag_list because it returned any post that contained any of the tags in the tag list (an OR filter), and I need an AND filter here.
This is my models:
class Tag(models.Model):
tag = models.CharField(max_length=19, choices=TagChoices.choices())
class Post(models.Model):
tags = models.ManyToManyField(Tag, related_name='posts', blank=True)
This is the Q object that is being passed in the filter query:
(AND: ('tags__tag', 'work'), ('tags__tag', 'friends')
Qobject like that: a filter is an existential quantifier, not a universal. It means you are looking for a singleTagthat has astagnameworkandfriendsat the same time.