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. 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
  • Make a book print as its title and author, like Dune by Frank Herbert.

This lesson's Run adds four books. Press Run and type Book.objects.all() in the Shell tab.

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