Django查询:按会话分组的最后收到的邮件

时间:2018-06-20 12:45:28

标签: python django

我的模特:

class Mail(models.Model):
    subject = models.CharField(max_length=300)
    message = models.TextField()
    receiver = models.ForeignKey(User, related_name='receiver', on_delete=models.CASCADE)
    sender = models.ForeignKey(User, related_name='sender', on_delete=models.CASCADE)
    sent_date = models.DateTimeField(auto_now_add=True)
    conversation = models.ForeignKey(Conversation, on_delete=models.CASCADE)
    read = models.BooleanField(default=False)

我的查询:

Conversation.objects.filter(mail__receiver=request.user).annotate(latest_msg=Max('mail__id')).values('id','mail__id','mail__subject','mail__message','mail__sender__username','mail__sent_date','mail__read').order_by('-latest_msg')

它返回所有对话,其中包含登录用户(request.user)收到的任何邮件。为什么?我想要按会话分组的最新收到的邮件,例如Gmail。

编辑: 这是本机查询:

Query: SELECT "app_conversation"."id", "app_mail"."id", "app_mail"."subject", "app_mail"."message", T6."username", "app_mail"."sent_date", "app_mail"."read" FROM "app_conversation" INNER JOIN "app_mail" ON ("app_conversation"."id" = "app_mail"."conversation_id") INNER JOIN "app_user" T6 ON ("app_mail"."sender_id" = T6."id") WHERE "app_mail"."receiver_id" = 1 GROUP BY "app_conversation"."id", "app_conversation"."owner_id", "app_conversation"."user_id", "app_conversation"."create_date", "app_conversation"."archived", "app_mail"."id", "app_mail"."subject", "app_mail"."message", T6."username", "app_mail"."sent_date", "app_mail"."read" ORDER BY MAX("app_mail"."id") DESC

1 个答案:

答案 0 :(得分:0)

我明白了。这是查询:

maxMailsIds = Conversation.objects.filter(mail__receiver=user).annotate(maxId=Max('mail__id')).values_list('maxId', flat=True)
items = Mail.objects.filter(id__in=maxMailsIds).order_by('-id').values('subject','message')