Agu Aguilar
Agu Aguilar

Reputation: 301

Django filter objects from many to many relationship

I'm having a problem when trying to filter over a many-to-many relationship.

This is my models.py:

class Member(models.Model):
    name = models.CharField(max_length=255)

class Talk(models.Model):
    members = models.ManyToManyField(Member)

I want to get the conversations in which two members are participating.

Here are the data I have:

{
    "pk": 2,
    "members": [
        36384,
        12626,
        48397
    ],
},
{
    "pk": 3,
    "members": [
        36384,
        12626,
        -89813,
        48397
    ],
}

I want to get conversations where the two specified members participate. My query was as follows:

Talk.objects.filter(members__in=[12626, -89813])

The result I get is the following:

<QuerySet [<Talk: 2>, <Talk: 3>, <Talk: 3>]>

How can I make the result to be this?

<Talk: 3>

Note: It is in the only conversation in which the specified members are participating

Thanks

Upvotes: 0

Views: 648

Answers (1)

pramod
pramod

Reputation: 1493

try below django query:

from django.db.models import Q

Talk.objects.filter(
    Q(members__id=12626) & Q(members__id=-89813)
)

Upvotes: 2

Related Questions