Skip to content

Instantly share code, notes, and snippets.

@pyshawon
Forked from jperelli/conditional_orderby.py
Created December 8, 2022 06:47
Show Gist options
  • Select an option

  • Save pyshawon/b8873d8c32e13d7c6ad3cab31f103874 to your computer and use it in GitHub Desktop.

Select an option

Save pyshawon/b8873d8c32e13d7c6ad3cab31f103874 to your computer and use it in GitHub Desktop.
Conditional order by in django's ORM
"""
Some table has two Date fields: expiredate and SALexpiredate
Both fields can be null
when SALexpiredate is not null, overrides expiredate
when ordering:
if SALexpiredate is not null, that field needs to be used
otherwise fallback to use expiredate
"""
from django.db.models import DateField, Case, When, F
queryset.annotate(
expiredate_salexpiredate=Case(
When(salexpiredate__isnull=False, then=F('salexpiredate')),
default=F('expiredate'),
output_field=DateField(),
),
).order_by('-expiredate_salexpiredate')
"""
This is a simpler approach for the same problem I didn't know I could do.
I think that this is far better, but the previous could be useful in some use cases.
"""
from django.db.models.functions import Coalesce
queryset.order_by(
Coalesce(
F('salexpiredate'),
F('expiredate')
).desc()
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment