如何在Django中创建对话收件箱 [英] How to create a conversation inbox in Django

查看:145
本文介绍了如何在Django中创建对话收件箱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Message 类,该类具有 fromUser toUser 文本 createdAt 字段。

I have a Message class which has fromUser, toUser, text and createdAt fields.

I想模仿whatsapp或iMessage或任何SMS收件箱,这意味着我想获取每次对话的最后一条消息。

I want to imitate a whatsapp or iMessage or any SMS inbox, meaning I want to fetch the last message for each conversation.

我尝试过:

messages = Message.objects.order_by('createdAt').distinct('fromUser', 'toUser')

但这不起作用,因为 SELECT DISTINCT ON表达式必须与初始ORDER BY表达式匹配错误。

But this doesn't work because of SELECT DISTINCT ON expressions must match initial ORDER BY expressions error.

我不太明白这是什么意思,我也尝试过:

I don't really understand what it means, I also tried:

messages = Message.objects.order_by('fromUser','toUser','createdAt').distinct('fromUser', 'toUser')

等等,但让我不要在这里用毫无意义的代码段模糊真正的话题。我该如何获得这种基本的或更佳的,众所周知的结果?

and such but let me not blur the real topic here with apparently meaningless code pieces. How can I achieve this basic or better said, general well-known, result?

推荐答案

您的第二种方法是正确的。 摘自Django文档

Your second method is correct. From the Django docs:


指定字段名称时,必须在QuerySet中提供order_by(),而order_by()中的字段必须以

When you specify field names, you must provide an order_by() in the QuerySet, and the fields in order_by() must start with the fields in distinct(), in the same order.

例如,SELECT DISTINCT ON(a)为您提供列a中每个值的第一行。如果不指定订单,则会得到一些任意行。

For example, SELECT DISTINCT ON (a) gives you the first row for each value in column a. If you don’t specify an order, you’ll get some arbitrary row.

这意味着您必须在order_by()中包含相同的列您要在distinct()方法中使用的方法。的确,您的第二个查询正确地包含了order_by()方法中的列:

This means that you must include the same columns in your order_by() method that you want to use in the distinct() method. Indeed, your second query correctly includes the columns in the order_by() method:

messages = Message.objects.order_by('fromUser','toUser','createdAt').distinct('fromUser', 'toUser')

为了获取最新记录,您需要按降序排列createdAt列。指定此顺序的方法是在order_by()方法中的列名称上包括减号(此处的文档中有一个示例)。这是用来以最新到第一个顺序获取邮件列表的最终形式:

In order to fetch the latest record, you need to order the createdAt column by descending order. The way to specify this order is to include a minus sign on the column name in the order_by() method (there is an example of this in the docs here). Here's the final form that you should use to get your list of messages in latest-first order:

messages = Message.objects.order_by('fromUser','toUser','-createdAt').distinct('fromUser', 'toUser')

这篇关于如何在Django中创建对话收件箱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆