Search code examples
djangomany-to-many

ManyToManyField, filtering by matching all related values


I have in my model to classes:

User: name
Pair: users=ManyToManyField(User)

I want to make working and in the next step optimal query which allows me to get all pairs of two users. This code of course not works, but shows my problem. The order of user_1 and user_2 is not important.

def get_pair_by_users(user_name_1, user_name_2):
    return Pairs.objects.filter(users__name=user_name_1 & users__name=user_name_2) 

Solution

  • You can filter with:

    def get_pair_by_users(user_name_1, user_name_2):
        return Pairs.objects.filter(
            users__name=user_name_1
        ).filter(
            users__name=user_name_2
        )

    It is important to work with two .filter(…) calls [Django-doc], since then we make two JOINs. Otherwise we will query for an item that has a user that has as name both user_name_1 and user_name_2, which of course does not make much sense.