Forked from yosemitebandit/order_by_ignoring_null.py
Created
August 18, 2021 21:34
-
-
Save chase2981/08c3c64648c1a2dcb2e6f4acc5b11d76 to your computer and use it in GitHub Desktop.
an example of ordering a Django queryset while ignoring null values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Order a queryset by last_active and make null values sort last.""" | |
import datetime | |
from django.db.models.functions import Coalesce | |
from app import models | |
# Coalesce works by taking the first non-null value. So we give it | |
# a date far before any non-null values of last_active. Then it will | |
# naturally sort behind instances of Box with a non-null last_active value. | |
# docs.djangoproject.com/en/1.8/ref/models/database-functions/#coalesce | |
the_past = datetime.datetime.now() - datetime.timedelta(days=10*365) | |
boxes = models.Box.objects.all().annotate( | |
new_last_active=Coalesce('last_active', Value(the_past))).order_by( | |
'-new_last_active') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment