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')
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')
- 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')
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!