Home >Database >Mysql Tutorial >How to Sort Database Records with NULLS LAST in Django?
Django: Implementing "NULLS LAST" Sorting
When sorting database records with PostgreSQL, there may be a need to specify the sorting behavior of null values. PostgreSQL offers the "NULLS LAST" option to place null values at the end of the sorted results.
Query with "NULLS LAST" in Django
To achieve this in Django, you can use the Expression.asc() or Expression.desc() methods. However, the "NULLS LAST" option was not supported in Django versions prior to 1.11.
Solution for Django 1.11 and Later
For Django versions 1.11 and later, you can use the following code:
from django.db.models import F MyModel.objects.all().order_by(F('price').desc(nulls_last=True))
The F('price').desc(nulls_last=True) expression sorts the prices in descending order, ensuring that null values appear at the end.
Reference
For further information:
The above is the detailed content of How to Sort Database Records with NULLS LAST in Django?. For more information, please follow other related articles on the PHP Chinese website!