Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
.
.
.
Yesterday
Yesterday -1

like image 797
Rodrigo Travessini Avatar asked Sep 17 '16 19:09

Rodrigo Travessini


Video Answer


1 Answers

Yes you can, what you want is the descending behavior of the 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.

In fact, combining queries using the | operator wouldn't preserve the order you want, so you can't do this with 2 django queries.

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. 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_bys in each queryset to order each part of the result as you want, for brevity of codes, I didn't write them here.

like image 189
SpiXel Avatar answered Oct 09 '22 07:10

SpiXel