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
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_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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With