How to create a conversation inbox in Django

时光怂恿深爱的人放手 提交于 2019-12-06 08:36:30

Your second method is correct. From the Django docs:

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.

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.

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')

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')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!