Menu
CoddyTech

How a Book Prints

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

Press Run and type Book.objects.all() in the Shell tab: every book reads <Book: Book object (1)>, and you cannot tell them apart. Book.objects.all() asks for every book; the next chapter explains it. Python turns an object into text with its __str__ method, and the one every model gets shows only the id. A model can define its own. A film site's Movie might print its title and year:

class Movie(models.Model):
    ...

    def __str__(self):
        return f"{self.title} ({self.released.year})"

The shell then shows <Movie: Alien (1979)>, and so do the admin and any template that prints {{ movie }}. __str__ must return the text. A method that prints it returns None, and str() then fails with a TypeError.

challenge icon

Challenge

Easy

In books/models.py, make a book print as its title, by, and its author: Dune by Frank Herbert.

Press Run and type Book.objects.all() in the Shell tab: each book now reads like <Book: Dune by Frank Herbert>.

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)

All lessons in Models and the Admin

Practice on your own: Django playground