Melissa Stewart
Melissa Stewart

Reputation: 3625

Multiple queries in django ORM

I have the following user model,

class User(AbstractBaseUser, PermissionsMixin, Base):
    email = models.EmailField(db_index=True, unique=True, max_length=255)
    mobile = PhoneNumberField(null=True)

and room model,

class Room(Base):
    name = models.CharField(db_index=True, unique=True, max_length=255)
    members = models.ManyToManyField(User)

I want to check if there exists a room which has both a and b as members. I tried this,

PrivateRoom.objects.filter(members__id=first.id, members__id=second.id).exists()

This gives me an error keyword argument repeated. Can someone help me with the query.

Upvotes: 2

Views: 4512

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477617

You need to split this over two .filter(..) calls:

PrivateRoom.objects.filter(members__id=first.id).filter(members__id=second.id).exists()

Not only because you can not used the same named argument in a Python function call, but if this is possible (it is with Q objects), it would mean you are looking for a single member with id both being equal to first.id and second.id.

This is not what you want: you want two different JOINs: one for the first member, and one for the second.

Upvotes: 2

Related Questions