Home > Database > Mysql Tutorial > How to Sort Database Records with NULLS LAST in Django?

How to Sort Database Records with NULLS LAST in Django?

Susan Sarandon
Release: 2024-12-28 15:27:26
Original
689 people have browsed it

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))
Copy after login

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:

  • Django 3.1 Expression Reference: [Django Documentation](https://docs.djangoproject.com/en/3.1/ref/models/expressions/#using-f-to-sort-null-values)
  • Django 1.11 Release Notes: [Django Documentation](https://docs.djangoproject.com/en/dev/releases/1.11/)

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template