[Django]-Django find exact match for Many To Many relationship

4👍

We can count how many members match the list, and check if that includes all the members:

from django.db.models import Count, Q

members = [1,2]
members_len = len(set(members))

Conversation.objects.annotate(
    total_members=Count('members'),
    matching_members=Count('members', filter=Q(members__in=members))
).filter(
    matching_members=members_len,
    total_members=members_len
)

This thus will retrieve Converstions that contain all members in the members list, and only these members (so not a superset, nor a subset).

Or for pre installations:

from django.db.models import Case, Count, When

members = [1,2]
members_len = len(set(members))

Conversation.objects.annotate(
    total_members=Count('members'),
    matching_members=Count(Case(
        When(members__in=members, then='members'),
        default=None
    ))
).filter(
    matching_members=members_len,
    total_members=members_len
)

Leave a comment