Django按向后的外键排序 [英] Django Sort by backward foreign key

查看:253
本文介绍了Django按向后的外键排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有以下模型:

I currently have the following models

class ChatRoom(models.Model):
      creator = models.ForeignKey('User') # points to the initial user

class Message(models.Model):
      room = models.ForeignKey('ChatRoom')
      text = models.CharField(max_length=500)
      date = models.DateTimeField()
      from = models.ForeignKey('User') # points to some user

对于登录到我的网站的任何给定的用户,我想显示他们创建的聊天室的列表,按照最后一条消息的日期排序(最新活动)以及输入到聊天室的最后一条消息

For any given user who logs into my website, I want to display a list of the chat rooms they have created, ordered by the date of their last message (latest activity) along with the last message entered to the chatroom

所以像

Your chat rooms
---------------
science - "hey guys, anyone know how to do calculus?" 5m
art     - "hey guys, I like art" 10m

在django中查询?请记住,一个人可能有许多,许多聊天室,因此我们不能只是加载所有的chat_rooms与 ChatRoom.objects.all()并手动迭代

How would I perform this query in django? Keep in mind that a person might have many, many, many chat rooms and thus we can't just load all the chat_rooms with ChatRoom.objects.all() and manually iterate through it.

推荐答案

您需要与上一条消息有其他关系,否则您将无法通过他们订购

You need to have a additional relation to your last message, otherwise you will not be able to order by them.

class ChatRoom(models.Model):
      creator = models.ForeignKey('User') # points to the initial user
      # you will need to set this in view or with signals.(don't forget to handle delete)
      last_message = models.ForignKey('Message')

你可以这样做

ChatRoom.objects.filter(...).order_by('last_message__date')

这篇关于Django按向后的外键排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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