Django filter query to get chat messages among two friends?

There’s one more condition that might need to be addressed. Is there any possibility for person to send a message to themself? In other words, do we need to be concerned about the case where sender_id == receiver_id?

If not, you can do this most easily with a couple of in clauses -
ChatMessage.objects.filter(sender__in=[sender_id, receiver_id], receiver__in=[sender_id, receiver_id])

There are other ways of writing this as well. You could also do this as a pair of Q clauses:
ChatMessage.objects.filter(Q(sender=sender_id, receiver=receiver_id)|Q(sender=receiver_id, receiver=sender_id))
This query will not include messages where sender==receiver, except for those cases where the query is issued with sender_id==receiver_id.

1 Like