10 views
Skip to first unread message

Aamu Padi

unread,
Dec 3, 2013, 5:41:30 PM12/3/13
to django...@googlegroups.com
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 all the threads of user1 and user2

    # Then this
    >>> Thread.objects.filter(Q(user=user1) | Q(user=user2)).distinct()
    # Just the same as the above, just without repeating the same threads.

What I want is to check the thread, with the specified users only. Suppose, User 1 wants to send a message to User 2. First it must 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? Please help me. Thank you.

And please tell me what's the difference between `|` and `&`? Because I had very different results with these two.
Reply all
Reply to author
Forward
0 new messages