django查询获取最后n条记录 [英] django query get last n records
本文介绍了django查询获取最后n条记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试过:
Messages.objects.filter(since = since)[: - 10]
我有一个错误,表示不支持排除索引。
我的当前的工作是排序ID降序,然后运行:
Messages.objects.filter(since = since)[:10 ]
但这需要前端再次扭转订单。
我的问题是,有优雅的方式吗?
解决方案
你可以传递你的查询颠倒:
last_ten = Messages.objects.filter(since = since).order_by(' - id')[:10]
last_ten_in_ascending_order = revers(last_ten)
Lets say I am implementing a message stream, records sort by ID ascending order, each fetch request, I want to only allow to fetch the most latest 10 records.
I tried:
Messages.objects.filter(since=since)[:-10]
And I had an error saying Negative Indexing is not supported.
My current work around is sort ID descending order, and then run:
Messages.objects.filter(since=since)[:10]
But this requires the front end to reverse the order again.
My question is, is there a elegant way to do it?
解决方案
You can pass your queryset to reversed:
last_ten = Messages.objects.filter(since=since).order_by('-id')[:10]
last_ten_in_ascending_order = reversed(last_ten)
这篇关于django查询获取最后n条记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文