Ordering Query Results with "NULLS LAST" in Django
When working with PostgreSQL, you may encounter a scenario where you desire to sort model results prioritizing non-null values over nulls using the "NULLS LAST" option.
Attempt and Issue
An initial approach using extra(order_by=('-price', 'NULLS LAST')) may result in the error, "Cannot resolve keyword 'NULLS LAST' into field."
Solution
To achieve the desired sorting behavior, utilize the following solution introduced in Django 1.11:
from django.db.models import F MyModel.objects.all().order_by(F('price').desc(nulls_last=True))
This syntax utilizes the F expression provided by Django, allowing you to specify field sorting with customizable parameters. The desc(nulls_last=True) argument ensures that null values are treated as the last elements in the sorted results.
Reference
For further information, refer to the official Django documentation for versions 1.11 and 3.1:
The above is the detailed content of How to Order Django Query Results with NULLS LAST in PostgreSQL?. For more information, please follow other related articles on the PHP Chinese website!