Django: how to order_by on a related field of a related field

跟風遠走 提交于 2019-12-05 05:03:09

Ok, apparently it is just 'discussion__discussionresponse__timestamp'. I tried it in the Django shell and it didn't work after saving a new DiscussionResponse, but it worked several minutes later when I tried it again:

>>> groups = Group.objects.all().annotate(last_response=Max(
        'discussion__discussionresponse__timestamp')).order_by('-last_response')
>>> for group in groups:
...     print(group.id, group.last_response)
...     
... 
(2L, datetime.datetime(2013, 5, 16, 14, 56, 22))
(1L, None)
(3L, None)
(4L, None)
(6L, None)
(7L, None)
(8L, None)
(9L, None)
>>> 

If anyone knows why it didn't work right after saving a new object to the database, but did work later, that would probably be useful information.

Here's another run at the query with discussions/responses added to another group just for added verification:

>>> groups = Group.objects.all().annotate(last_response=Max('discussion__discussionresponse__timestamp')).order_by('-last_response')
>>> for group in groups:
...     print(group.id, group.last_response)
...     
... 
(4L, datetime.datetime(2013, 5, 16, 15, 25, 40))
(2L, datetime.datetime(2013, 5, 16, 15, 16, 46))
(1L, None)
(3L, None)
(6L, None)
(7L, None)
(8L, None)
(9L, None)
>>> 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!