[Fixed]-Django queryset order_by dates near today

41👍

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.

👤SpiXel

Leave a comment