About NULLS FIRST and NULLS LAST in QuerySet Ordering

When you sort a QuerySet by a field, you can define whether NULL values should come first or last like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
from django.db import models
from feedback.models import FeedbackMessage

# messages from non-authenticated people last
messages = FeedbackMessage.objects.order_by(
    models.F("user__username").asc(nulls_last=True)
)

# messages from non-authenticated people first
messages = FeedbackMessage.objects.order_by(
    models.F("user__username").asc(nulls_first=True)
)

Tips and Tricks Programming Databases Django 4.2 Django 3.2 Django 2.2 PostgreSQL MySQL