Django Sort by backward foreign key

前端 未结 1 534
一个人的身影
一个人的身影 2021-01-28 12:54

I currently have the following models

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

class Message(model         


        
相关标签:
1条回答
  • 2021-01-28 13:49

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

    And that you can do this

    ChatRoom.objects.filter(...).order_by('last_message__date')
    
    0 讨论(0)
提交回复
热议问题