Z
Z
zxmd2014-03-19 12:26:07
Django
zxmd, 2014-03-19 12:26:07

Django ManyToMany relation - how to select by AND?

Hello.
Perhaps this will seem banal to someone, but there is the following problem:
There is a model:

class Room(models.Model):
    users = models.ManyToManyField(User, related_name='speakers')
    ....

I just can’t figure out how to make such a selection through ORM or even through SQL (in a word, not pythonic logic): you
need the Room in which there are 2 different users and only them.
That is, the case:
Room1 - with users = [user1,user2,user3]
Room2 - with users = [user1,user3]
Room3 - with users = [user1,user2]
Let's say I need to find only those rooms that have user1 and user2, that is, only Room3.
Through __in, of course, it will not be the same, through Q() & Q() - too.
If anyone knows a solution in SQL, please share. Base PG9.1
So far I have found only such a crooked solution:
SELECT * FROM (
SELECT messages_rooms_users.room_id, COUNT(messages_rooms_users.room_id) as ctx from messages_rooms_users
WHERE
messages_rooms_users.user_id in (__users_id_list__)
GROUP BY messages_rooms_users.room_id) as subq
WHERE subq.ctx = 2

Maybe someone will tell.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey K, 2014-03-19
@zxmd

from django.db.models import Count
Room.objects.annotate(num_users=Count('users').filter(users=user1).filter(users=user2, num_users=2)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question