[Answer]-Django QuerySet: filter by date, then select one more

1👍

You probably would not be able to do it with one database call, as there is no way to know what the next date would be ahead of time, unless you do some preprocessing.

One way is:

next = Resource.objects.filter(date__gt=now()).order_by('date')[:1]
archive = Resource.objects.filter(date__lt=now())
qs = list(chain(archive, next))

OR

qs = list(archive, next)

Another approach involving a quick lookup would be

dt = None
now = now()

next = Resource.objects.filter(date__gt=now()).order_by('date')[:1]
if next.exists(): #A quick lookup for the date
    now = next[0].date

archive = Resource.objects.filter(date__lt=now).order_by('date')

Leave a comment