Django queryset get exact manytomany lookup [duplicate]

One approach is to use chain of filters:

node_query = Node.objects.all()
pk_list = [10, 6, 3]

for pk in pk_list:
    node_query = node_query.filter(tags=pk)

Now node_query will match node, that has at least three tags with pk 10, 6, 3. To exact matching of three tags:

UPDATE:
Thanks to @janos and @Adrián López, the correct answer is:

from django.db.models import Count

pk_list = [10, 6, 3]
node_query = Node.objects.annotate(count=Count('tags')).filter(count=len(pk_list))

for pk in pk_list:
    node_query = node_query.filter(tags__pk=pk)

Leave a Comment