Django queryset order_by dates near today
<p>I want to show the records near to today's date at top and then all records in the past at bottom:</p>

<p>Today<br>
Tomorrow<br>
Tomorrow + 1<br>
.<br>
.<br>
.<br>
Yesterday<br>
Yesterday -1 </p>

<p>Yes you can, what you want is the descending behavior of the <strong><a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#django.db.models.query.QuerySet.order_by" rel="nofollow">order_by</a></strong>.</p>

<p><strong>Oldest items first.</strong></p>

<pre><code>Model.objects.order_by('creation_time')
</code></pre>

<p><strong>Newest items first.</strong> (what you want)</p>

<pre><code>Model.objects.order_by('-creation_time')
</code></pre>

<p><strong>For Your Edit</strong></p>

<p>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.</p>

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

<pre><code>qset = Model.objects.all()
result = qset.filter(creation=today) | qset.filter(creation_gte=today) | qset.filter(creation_lt=today)
</code></pre>

<p>The following <code>result</code> would contain all items you'd want, but won't preserve single queryset ordering. So, not gonna do what you want from it.</p>

<p>So in summary, you have to evaluate the querysets, and add them together as lists to achieve what you want.</p>

<pre><code>qset = Model.objects.all()
result = list(qset.filter(creation=today)) + list(qset.filter(creation_gte=today)) + list(qset.filter(creation_lt=today))
</code></pre>

<p>or in a nicer fashion:</p>

<pre><code>import itertools
result = list(itertools.chain(qset.filter(creation=today), qset.filter(creation_gte=today), qset.filter(creation_lt=today)))
</code></pre>

<p>Don't forget to do the <code>order_by</code>s in each queryset to order each part of the result as you want, for brevity of codes, I didn't write them here.</p>

python django sorting sql-order-by