0

I have a queryset that I am ordering by -DateTimeField

model:

class QuestSubmission(models.Model):
    quest = models.ForeignKey(Quest)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, 
    ...
    time_returned = models.DateTimeField(null=True, blank=True)

queryset:

QuestSubmission.objects.all().order_by('-time_returned')

In my sqlite3 tests, this order newest to oldest followed by None/Null entries

But on my Postgresql server the order is None/Null then newest to oldest.

How can I get my postgresql order_by to place the None/Null values at the end similar to the sqlite3?

1

1 Answer 1

1

Something like this should work.

select * from dude order by case when date is null then 1 else 0 end, date desc;
 test  |    date    
-------+------------
 test2 | 2001-01-04
 test2 | 2001-01-03
 test2 | 2001-01-02
 test2 | 2001-01-01
 test  | 
 test2 | 

example:

from django.db.models import Case, When, Value, IntegerField

SomeModel.objects.annotate(
    nulls_last=Case(
        When(time_returned__isnull=True, then=Value(1)),
        When(time_returned__isnull=False, then=Value(0)),
        output_field=IntegerField(),
    )
).order_by('nulls_last', '-time_returned')

from here: Django order_by specific order

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.