Django QuerySet – Order By

Welcome to The Coding College, where we make coding concepts easy to grasp. In this tutorial, we’ll focus on Django’s order_by() method, which allows you to sort data retrieved from the database using QuerySets.

What is order_by()?

The order_by() method is used to sort QuerySet results based on one or more fields. Sorting can be done in ascending or descending order.

Syntax

Model.objects.order_by(field_name)  

Example Model

Here’s an example model that we’ll use in this tutorial:

from django.db import models  

class Product(models.Model):  
    name = models.CharField(max_length=100)  
    price = models.DecimalField(max_digits=10, decimal_places=2)  
    stock = models.IntegerField()  
    created_at = models.DateTimeField(auto_now_add=True)  

Sorting Data

1. Ascending Order

By default, order_by() sorts data in ascending order.

from .models import Product  

# Sort products by price in ascending order  
products = Product.objects.order_by('price')  

for product in products:  
    print(product.name, product.price)  

2. Descending Order

To sort in descending order, prefix the field name with a minus (-) sign.

# Sort products by price in descending order  
products = Product.objects.order_by('-price')  

for product in products:  
    print(product.name, product.price)  

Sorting by Multiple Fields

You can sort by multiple fields by passing them as arguments to order_by().

Example

# Sort by stock (ascending), then by price (descending)  
products = Product.objects.order_by('stock', '-price')  

for product in products:  
    print(product.name, product.stock, product.price)  

In this case:

  • Products are sorted by stock in ascending order.
  • If two products have the same stock value, they are further sorted by price in descending order.

Removing Default Ordering

If your model has a Meta class with ordering defined, it will apply default sorting to all QuerySets. To override this, use none().

Example

class Product(models.Model):  
    name = models.CharField(max_length=100)  
    price = models.DecimalField(max_digits=10, decimal_places=2)  
    class Meta:  
        ordering = ['name']  

# Override default ordering  
products = Product.objects.all().order_by()  

Case-Insensitive Sorting

To perform case-insensitive sorting, use the Lower() function from django.db.models.functions.

Example

from django.db.models.functions import Lower  

# Sort product names in case-insensitive order  
products = Product.objects.order_by(Lower('name'))  

for product in products:  
    print(product.name)  

Combining with Filters

You can chain filter() and order_by() to retrieve and sort data simultaneously.

Example

# Products priced above $100, sorted by price (descending)  
products = Product.objects.filter(price__gt=100).order_by('-price')  

for product in products:  
    print(product.name, product.price)  

Random Order

To retrieve QuerySet results in a random order, use the ? operator.

Example

# Get products in random order  
products = Product.objects.order_by('?')  

for product in products:  
    print(product.name)  

Caution: Using ? can be slow for large datasets as it does not leverage database indexing.

Limiting Results

To retrieve only the top results after sorting, use slicing.

Example

# Get the top 5 most expensive products  
products = Product.objects.order_by('-price')[:5]  

for product in products:  
    print(product.name, product.price)  

Advanced Sorting Techniques

1. Sorting by Annotated Fields

Use annotated fields in sorting for complex queries.

from django.db.models import F  

# Sort by stock minus 10  
products = Product.objects.annotate(stock_adjusted=F('stock') - 10).order_by('stock_adjusted')  

2. Sorting with Aggregates

Sort QuerySets using aggregate functions like Sum or Count.

from django.db.models import Count  

# Sort categories by the number of products  
categories = Category.objects.annotate(product_count=Count('product')).order_by('-product_count')  

Performance Considerations

  • Database Indexing: Ensure indexed fields are used for sorting large datasets.
  • Limit Fields: Use .only() or .defer() to fetch only necessary fields.

Learn More at The Coding College

Dive deeper into Django QuerySets and advanced database operations at The Coding College. We provide tutorials, guides, and hands-on examples to help you excel in web development.

Final Thoughts

The order_by() method is a powerful way to sort QuerySet results in Django. By mastering its features, you can retrieve data efficiently and present it in a meaningful order for your users.

For more insights and tutorials, stay connected with The Coding College. Let us know if you’d like to explore more about QuerySets or other Django topics!

Leave a Comment