Anirban
Anirban

Reputation: 176

How to order in django on two columns when one of the column is null

I would like to order the dataset based upon the two columns let's say created_date and updated_date.

If updated_date is null it should order be using created_date otherwise using updated_date column.

Upvotes: 2

Views: 37

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477160

You can work with a .annotate() [Django-doc] and then .order_by(…) [Django-doc]:

from django.db.models.functions import Coalesce

MyModel.objects.annotate(
    my_date=Coalesce('updated_date', 'created_date')
).order_by('my_date')

Since you can work with .alias(…) [Django-doc] to prevent calculating this both as column and in the ORDER BY clause:

from django.db.models.functions import Coalesce

MyModel.objects.alias(
    my_date=Coalesce('updated_date', 'created_date')
).order_by('my_date')

Upvotes: 2

Related Questions