Home >Database >Mysql Tutorial >How to Sort NULL Values Last in Django Queries with PostgreSQL?

How to Sort NULL Values Last in Django Queries with PostgreSQL?

Susan Sarandon
Susan SarandonOriginal
2024-12-29 14:19:18405browse

How to Sort NULL Values Last in Django Queries with PostgreSQL?

How to Add "NULLS LAST" to a Django Query

When sorting data in PostgreSQL, it is common practice to use the "NULLS LAST" option to ensure that null values are sorted at the end of the results. This option is not directly supported in Django's query API.

Solution

The nulls_last=True parameter can be used with Expression.desc() to control the ordering of null values. Here's an example:

from django.db.models import F

MyModel.objects.all().order_by(F('price').desc(nulls_last=True))

This syntax has been available since Django 1.11.

Additional Information

The docs recommend using Expression.asc() or Expression.desc() with the appropriate nulls_last parameter instead of extra() with the legacy order_by syntax.

For Django 3.1 and above, refer to the official documentation for more information:

https://docs.djangoproject.com/en/3.1/ref/models/expressions/#using-f-to-sort-null-values

The above is the detailed content of How to Sort NULL Values Last in Django Queries with PostgreSQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn