I'm creating a private user to user chat, in order to chat with someone the connected user has to type the username of the user with whom he wants to talk to on his own url.
Now that this system is already built, I want to keep a chat history so that later on I can send notification of chat. To do that I need to get the last message of each conversations and I want to show it on the connected user's own chat profile.
Just as the image below :
Model userComment
fields are : recipient
, sender
, comment
, sent_at
views.py :
def inbox(request, username):
username = User.objects.get(username=username)
connected_user = request.user
if username == connected_user:
#I'm having the issue on this line
users = userComment.objects.filter(Q(client=request.user) | Q(worker=request.user)).order_by(?)
else:
users = userComment.objects.filter(Q(Q(client=request.user) & Q(worker=username)) | Q(Q(client=username) & Q(worker=request.user))).order_by('sent_at')
models.py
class userComment(models.Model):
client = models.ForeignKey(User, related_name="client")
worker = models.ForeignKey(User, blank=True, null=True, related_name="worker")
sent_at = models.DateTimeField(auto_now_add=True)
comment = models.TextField(max_length=255, null=True)
def __str__(self):
return str(self.client)
Question : How can I filter and order my view to do so ?
Firstly in your
userComment
model add a related query name for reverse relationNow in your
views.py
use this query:Set the appname in extra according to name of the
app
in which the model is.Now you can access it as follows: