Django - How to query where only the described objects exist in many areas

How to check whether there is threadone containing only sender(user 1) and recipient(user 2), and 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.

I want to check the stream with the specified users. Suppose user 1 wants to send a message to user 2. I want to first check if there is a thread between both users. If there is, get this thread or create a new one. How is this possible? What is the best way to do this. Please help me. Thanks.

And please tell me, what is the difference between |and &? Because I had 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>]

, a b, . : t1 t4. , . .

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

, 1 2. , , , .

, , , , .

postgresql, , ( ):

threads = Message.objects.filter(sender=user1) \
                         .filter(thread__user=user2)
                         .distinct('thread')

, :

thread_ids = set(Message.objects.filter(sender=user1) \
                         .filter(thread__user=user2)
                         .values_list('thread__pk', flat=True))
threads = list(Thread.objects.get(pk=i) for i in thread_ids)

if not threads:
    # create a new thread
else:
    # Choose from one of the existing threads

; , - :

threads.filter(user__in=[user1, user2])
+1

All Articles