Home > Backend Development > Python Tutorial > Django: Ordering queryset by ascending and descending

Django: Ordering queryset by ascending and descending

WBOY
Release: 2024-08-08 06:43:12
Original
884 people have browsed it

Django: Ordenando queryset por ascendente e descendente

1. Ascending order

Ascending order, also known as "ascending order" in English, is a way of organizing a sequence of items in an ascending manner, from smallest to largest.

Product.objects.all().order_by('name')
Copy after login

2. Descending order

Descending order, also known as "descending order" in English, is a way of organizing a sequence of items in a descending manner, from largest to smallest.

Product.objects.all().order_by('-name')
Copy after login

- is used to indicate descending order.

In addition, we can use other attributes of the Product model as ordering and tiebreaker criteria. Imagine that we have two products with the same name, but with different prices.

Nome Dt. de criação
Produto A 2024-08-01
Produto A 2024-08-02
Produto B 2024-08-03
Produto C 2024-08-04
Produto D 2024-08-05

And as a criterion, display the products by Dt. most recently created. This way, we can implement it like this:

Product.objects.all().order_by('name', '-created_at')
Copy after login

The expected result of the listing will be as follows:

Nome Dt. de criação
Produto A 2024-08-02
Produto A 2024-08-01
Produto B 2024-08-03
Produto C 2024-08-04
Produto D 2024-08-05

The above is the detailed content of Django: Ordering queryset by ascending and descending. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template