django - How to query where just the described objects exist in a many to many field

django, django-models, django-orm, django-views

Solution

excludedUsers = Users.objects.exclude(id__in=[user1.id, user2.id])
Thread.objects.filter(users=user1).filter(users=user2).exclude(users__in=excludedUsers)

Problem

How do I check whether there is a `thread` containing only the `sender` (user 1) and the `recipient` (user 2), and no other users. models.py ``` class Thread(models.Model): user = models.ManyToManyField(User) is_hidden = models.ManyToManyField(User, related_name='hidden_thread', blank=True) class Message(models.Model): thread = models.ForeignKey(Thread) sent_date = models.DateTimeField(default=datetime.now) sender = models.ForeignKey(User) body = models.TextField() is_hidden = models.ManyToManyField(User, related_name='hidden_message', blank=True) ``` I tried ``` >>> Thread.objects.filter(user=user1&user2) >>> Thread.objects.filter(user=user1|user2) # Both gave me an error: Unsupported operand. # Then this >>> Thread.objects.filter(Q(user=user1) & Q(user=user2)) # Which gave me no threads at all. # Then this >>> Thread.objects.filter(Q(user=user1) | Q(user=user2)).distinct() # Gave me threads of both the users. ``` What I want is to check the thread, with the specified users only. Suppose, User 1 wants to send a message to User 2. What I want is, first check whether there is a thread between both the users. If there is, get that thread, or else create a new one. How is it possible? What is the best way to do it. Please help me. Thank you. And please tell me what's the difference between `|` and `&`? Because I had very different results with these two. Edit: ``` >>> t1 = Thread.objects.get(id=1) >>> t1 [<User: a>,<User: b>] >>> t2 = Thread.objects.get(id=2) >>> t2 [<User: a>,<User: b>,<User: c>] >>> t3 = Thread.objects.get(id=3) >>> t3 [<User:a>,<User: c>] >>> t4 = Thread.objects.get(id=4) >>> t4 [<User:a>,<User:b>] ``` What I want is to get the thread where just the user `a` and user `b` exist, and no other users. In this case, it would be: `t1` and `t4`. Hope I made myself clear. Thank you.

Original source