Peter
Peter

Reputation: 11

Filtering with Django-Taggit: Is it possible to filter for model entries that include all tags?

The code:

Food.objects.filter(tags__name__in=["Tag 1","Tag 2","Tag 3"]).distinct()

More precisely, if I want to filter for Food(s) where Food(s) has at least all three tags (not just one or two of the three, but could have more than the three), is there a modification to the filter provided in docs that achieves this result?

http://django-taggit.readthedocs.io/en/latest/api.html

Upvotes: 1

Views: 1914

Answers (1)

badiya
badiya

Reputation: 2257

Try:

tag_list = ["Tag 1","Tag 2","Tag 3"]

one way is to use multiple filters in a chained manner. Like this

Food.objects.filter(tags__name=tag_list[0]).filter(tags__name=tag_list[1]).filter(tags__name=tag_list[3]).distinct()

another way is to use annotation approach

Food.objects.filter(tags__name__in=tag_list).annotate(num_tags=Count('tags')).filter(num_tags__gte=len(tag_list)).distinct()

Upvotes: 3

Related Questions