如何在Django中创建对话收件箱

编程入门 行业动态 更新时间:2024-10-26 06:36:20
本文介绍了如何在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中创建对话收件箱

本文发布于:2023-10-25 18:32:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1527751.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:收件箱   如何在   Django

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!