1

Here's my Model

class Message(models.Model):
    sender = models.ForeignKey(User, related_name="sender")
    receiver = models.ForeignKey(User, related_name="receiver")
    msg_content = models.TextField()

How can I filter out the Users only if, either Current User have sent them a message or they have sent Current User a message, as we see on our Social Networks?

wencakisa
  • 5,850
  • 2
  • 15
  • 36

2 Answers2

2

You can use filter() in combination with the Q object, which allows you to make more complex queries (in your case, an OR expression):

>>> from django.db.models import Q
>>> user = request.user  # Take the current user
>>> Message.objects.filter(Q(sender=user) | Q(receiver=user))  # Filter messages where the sender or the receiver is the current user
<QuerySet [...]>
wencakisa
  • 5,850
  • 2
  • 15
  • 36
  • Sir, I have even used .distinct() but why it's filtering out the user equal number times as the number of messages sent ? –  Aug 31 '17 at 10:40
  • @ShivamKumarDodval I think you should use `.distinct('sender')`. – wencakisa Aug 31 '17 at 10:47
  • Sir, it's raising an error "NotImplementedError at /messages/, DISTINCT ON fields is not supported by this database backend". I'm currently using sqlite3. –  Aug 31 '17 at 10:56
  • @ShivamKumarDodval Then I think you should perform and **exclusive OR**, not **OR**. Look at this: https://stackoverflow.com/questions/14711203/perform-a-logical-exclusive-or-on-a-django-q-object – wencakisa Aug 31 '17 at 12:48
0

Try something like this : 1. user_obj = User.objects.filter(sender__receiver__pk= request.user.id) 2. users = User.objects.filter(sender__receiver= request.user)

Ravi
  • 216
  • 3
  • 11