简体   繁体   English

Django queryset order_by 日期接近今天

[英]Django queryset order_by dates near today

I want to show the records near to today's date at top and then all records in the past at bottom:我想在顶部显示接近今天日期的记录,然后在底部显示过去的所有记录:

Today今天
Tomorrow明天
Tomorrow + 1明天+1
. .
. .
. .
Yesterday昨天
Yesterday -1昨天-1

Yes you can, what you want is the descending behavior of the order_by .是的,你可以,你想要的是order_by的降序行为。

Oldest items first.首先是最古老的项目。

Model.objects.order_by('creation_time')

Newest items first.最新商品优先。 (what you want) (你想要什么)

Model.objects.order_by('-creation_time')

For Your Edit供您编辑

You have to make two queries and then evaluate them to lists to do what you wat, you can't do such thing with django ORM's queries.您必须进行两个查询,然后将它们评估为列表以执行您所需要的操作,您不能使用 django ORM 的查询来做这样的事情。

In fact, combining queries using the |事实上,使用|组合查询operator wouldn't preserve the order you want, so you can't do this with 2 django queries.运算符不会保留您想要的顺序,因此您不能使用 2 django 查询来执行此操作。

qset = Model.objects.all()
result = qset.filter(creation=today) | qset.filter(creation_gte=today) | qset.filter(creation_lt=today)

The following result would contain all items you'd want, but won't preserve single queryset ordering.以下result将包含您想要的所有项目,但不会保留单个查询集排序。 So, not gonna do what you want from it.所以,不会做你想做的事。

So in summary, you have to evaluate the querysets, and add them together as lists to achieve what you want.所以总而言之,您必须评估查询集,并将它们作为列表添加在一起以实现您想要的。

qset = Model.objects.all()
result = list(qset.filter(creation=today)) + list(qset.filter(creation_gte=today)) + list(qset.filter(creation_lt=today))

or in a nicer fashion:或者以更好的方式:

import itertools
result = list(itertools.chain(qset.filter(creation=today), qset.filter(creation_gte=today), qset.filter(creation_lt=today)))

Don't forget to do the order_by s in each queryset to order each part of the result as you want, for brevity of codes, I didn't write them here.不要忘记在每个查询集中执行order_by以根据需要对结果的每个部分进行排序,为了代码简洁,我没有在这里写它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM