Click here to Skip to main content
15,885,216 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to build a messaging app. 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()
created_at = models.DateTimeField(auto_now_add=True)

This is what I tried in view,

data = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user))

In the template,

{% for abc in data %}
{{ abc.receiver }}

{% endfor %}

Here i wants to filter the distinct receivers and re-order them based upon the fact that to whom `request.user` sent new message recently (as we see on social media platforms). How can I do that?

I'm hanged with this code from 1 month, I will be very thankful with every little help :)

What I have tried:

data = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user)).values('receiver').distinct().order_by()

Also I tried,

data = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user))
receiver_list =
data.filter(sender=request.user).order_by('created_at').distinct('receiver')
Posted
Updated 27-Nov-17 21:53pm

1 solution

In the template, use an if condition that checks your receiver and sender for a particular message.
Something like

Python
{% if abc.receiver == request.user %}
# this means that the current user is the receiver
{% endif %}


Similarly you should be able to do it for abc.sender.

You'll need to pass current logged in user in the context(in your view).
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900