我正在爲用戶聊天創建一個私人用戶,爲了與某人聊天,所連接的用戶必須輸入用戶的用戶名,並與他想要在他自己的網址上進行交談。如何向用戶對話顯示每個用戶的最後一條消息以保存聊天記錄?
既然這個系統已經建好了,我想保留一個聊天記錄,以便稍後我可以發送聊天通知。爲此,我需要獲取每個對話的最後一條消息,並且我想在連接的用戶自己的聊天檔案中顯示它。
正如下面的圖片:
型號userComment
領域是: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)
問:如何才能篩選並訂購我認爲這樣做呢?在額外按名稱
user = request.user
users = User.objects.filter(Q(r__sender=user) | Q(s__recipient=user)).distinct().extra(select={'last_message_time': 'select MAX(sent_at) from appname_usercomment where (recipient_id=auth_user.id and sender_id=%s) or (recipient_id=%s and sender_id=auth_user.id)'}, select_params=(user.id, user.id,)).extra(order_by=['-last_message_time']).extra(select={'message': 'select comment from appname_usercomment where (sent_at=(select MAX(sent_at) from appname_usercomment where (recipient_id=auth_user.id and sender_id=%s) or (recipient_id=%s and sender_id=auth_user.id)) and ((recipient_id=auth_user.id and sender_id=%s) or (recipient_id=%s and sender_id=auth_user.id)))',}, select_params=(user.id, user.id,user.id, user.id,))
設置應用程序的名字:
不行的,這隻能得到所有查詢的最後一個項目。我希望它得到每個不同的消息集的最後一個項目,再加上如果它是由日期時間排序,然後有一個巨大的問題是,你可以在一個錯誤的收件箱中收到來自其他用戶的消息。 – Lindow
@KasimovNuriddin請張貼UserComment在模型 – eskawl
我已經張貼模型 – Lindow