Menu
CoddyTech

Default Order

Part of the Models and the Admin section of Coddy's Django journey. Lesson 6 of 23.

Your books come back in no promised order: whatever the database gives. A model can set the order once, for every query that does not ask for another. Options for the whole model, rather than one field, go in an inner class named Meta:

class Movie(models.Model):
    ...

    class Meta:
        ordering = ["-released", "title"]

ordering is a list of field names. A name alone sorts from low to high, A to Z for text; a minus in front sorts the other way, so this lists the newest films first. The second name breaks ties: films out on the same day come A to Z.

challenge icon

Challenge

Easy

In books/models.py, make books come back in title order, A to Z, whenever no order is asked for.

Press Run and type Book.objects.all() in the Shell tab: Dune comes first and The Hobbit last.

Try it yourself

from django.db import models


class Book(models.Model):
    class Genre(models.TextChoices):
        FICTION = "fiction", "Fiction"
        SCIFI = "scifi", "Science fiction"
        MYSTERY = "mystery", "Mystery"
        HISTORY = "history", "History"

    title = models.CharField(max_length=200)
    author = models.CharField(max_length=100)
    year = models.IntegerField()
    price = models.DecimalField(max_digits=6, decimal_places=2)
    is_read = models.BooleanField(default=False)
    finished = models.DateField(null=True, blank=True)
    summary = models.TextField(blank=True)
    genre = models.CharField(max_length=20, choices=Genre, default=Genre.FICTION)

    def __str__(self):
        return f"{self.title} by {self.author}"
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Models and the Admin

Practice on your own: Django playground