django - 切片后重新排序queryset [英] django - reorder queryset after slicing it
问题描述
qs = Foo.objects .all()[:5]
在下面的步骤中,我想重新排序一些查询其他条件(实际上是相反的datetime字段)。但不允许重新排序片断。 reverse()撤消第一个排序,给我一个不同的查询。有没有办法完成我想要的,而不是从查询器中创建列表,并使用它进行排序?
没有办法做到这一点 order_by
是数据库上的一个操作,但是当您切片查询器时,它被评估,之后不会返回到数据库。
听起来你已经知道解决方案,但是在评估的qs上运行 revers()
。
qs = revers(Foo.objects.all()[:5])
I fetch the latest 5 rows from a Foo model which is ordered by a datetime field.
qs = Foo.objects.all()[:5]
In the following step, I want to reorder the queryset by some other criteria (actually, by the same datetime field in the opposite direction). But reordering after a slice is not permitted. reverse() undoes the first ordering, giving me a differet queryset. Is there a way to accomplish what I want without creating a list from the queryset and doing the ordering using it?
No, there's no way of doing that. order_by
is an operation on the database, but when you slice a queryset it is evaluated and doesn't go back to the database after that.
Sounds like you already know the solution, though: run reversed()
on the evaluated qs.
qs = reversed(Foo.objects.all()[:5])
这篇关于django - 切片后重新排序queryset的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!