0
0
Djangoframework~5 mins

Ordering and slicing querysets in Django

Choose your learning style9 modes available
Introduction

Ordering and slicing help you get data from the database in the order and amount you want. This makes your app faster and easier to use.

When you want to show a list of items sorted by date or name.
When you need only the first few results, like top 5 products.
When you want to skip some items and get the next set, like pages in a list.
When you want to display data in a specific order, such as newest first.
When you want to limit the data sent to the user to improve speed.
Syntax
Django
Model.objects.order_by('field_name')[start:end]

Use order_by() to sort results by one or more fields.

Use slicing [start:end] to get a subset of results, like a list slice.

Examples
Get all books ordered alphabetically by title.
Django
Book.objects.order_by('title')
Get all books ordered by published date, newest first (descending).
Django
Book.objects.order_by('-published_date')
Get the first 5 books ordered by author name.
Django
Book.objects.order_by('author')[0:5]
Get books from 11th to 20th without ordering (default order).
Django
Book.objects.all()[10:20]
Sample Program

This example shows how to get books sorted by newest published date first, then take only the first two books from that list. It prints their title, author, and date.

Django
from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)
    published_date = models.DateField()

# Imagine we have these books in the database:
# 1. Title: 'A Tale of Two Cities', Author: 'Charles Dickens', Date: 1859-04-30
# 2. Title: 'Moby Dick', Author: 'Herman Melville', Date: 1851-10-18
# 3. Title: 'Pride and Prejudice', Author: 'Jane Austen', Date: 1813-01-28

# Get books ordered by published_date descending (newest first)
books = Book.objects.order_by('-published_date')

# Get the first 2 books from this ordered list
top_two_books = books[:2]

for book in top_two_books:
    print(f"{book.title} by {book.author} ({book.published_date})")
OutputSuccess
Important Notes

Slicing querysets uses zero-based indexing like Python lists.

Ordering by multiple fields is possible: .order_by('field1', '-field2').

Negative sign - before field name means descending order.

Summary

Use order_by() to sort your data by one or more fields.

Use slicing [start:end] to get only part of the data.

Ordering and slicing together help you show data in the right order and amount.