Home > Database > Mysql Tutorial > How to Order Django Query Results with NULLS LAST in PostgreSQL?

How to Order Django Query Results with NULLS LAST in PostgreSQL?

Linda Hamilton
Release: 2024-12-30 22:32:11
Original
768 people have browsed it

How to Order Django Query Results with NULLS LAST in PostgreSQL?

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

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:

  • Django 1.11: https://docs.djangoproject.com/en/dev/releases/1.11/#expression-asc-and-desc-nulls-first-and-nulls-last-parameters
  • Django 3.1: 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 Order Django Query Results with NULLS LAST in PostgreSQL?. 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