class Tag(models.Model): name = models.CharField(maxlength=100) class Blog(models.Model): name = models.CharField(maxlength=100) tags = models.ManyToManyField(Tag)
Simple models just to ask my question.
I wonder how can i query blogs using tags in two different ways.
- Blog entries that are tagged with ‘tag1’ or ‘tag2’:
Blog.objects.filter(tags_in=[1,2]).distinct() - Blog objects that are tagged with ‘tag1’ and ‘tag2’ : ?
- Blog objects that are tagged with exactly ‘tag1’ and ‘tag2’ and nothing else : ??
Tag and Blog is just used for an example.
You could use Q objects for #1:
Unions and intersections, I believe, are a bit outside the scope of the Django ORM, but its possible to to these. The following examples are from a Django application called called django-tagging that provides the functionality. Line 346 of models.py:
For part two, you’re looking for a union of two queries, basically
For part #3 I believe you’re looking for an intersection. See line 307 of models.py