这是我的模特,
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)
我想根据向request.user
发送邮件的人或最近向request.user
发送邮件的用户订购用户!正如我们在社交网络上看到的那样。
这就是我试过的,
users = User.objects.filter(Q(sender__receiver=request.user) | Q(receiver__sender=request.user)).annotate(Max('receiver')).order_by('-receiver__max')
此代码仅在request.user
向某人发送消息时才能正常工作。如果有人向request.user
发送消息,则不会更改消息的顺序。
我也试过了,
users = Message.objects.filter(sender=request.user, receiver=request.user).order_by("created_at")
但是,我无法过滤掉不同的用户。它显示的消息数量与用户数相同。
如何解决此问题?谢谢!
答案 0 :(得分:0)
我在尝试查找经过身份验证的用户的对话时遇到了同样的问题。我使用了以下解决方案:
def is_message_in_list(self, conversations, message):
for msg in conversations:
if (msg.sender == message.sender and msg.receiver == message.receiver) or \
(msg.sender == message.receiver and msg.receiver == message.sender):
return True
return False
def get(self, request):
user = request.user
messages = Message.objects.filter(
Q(sender=user) | Q(receiver=user)
).order_by('-created_at').select_related('sender', 'receiver')
conversations = []
for message in messages:
if not self.is_message_in_list(conversations, message):
conversations.append(message)