Menu
CoddyTech

Bookの表示方法

CoddyのDjangoジャーニー「モデルと管理サイト」セクションの一部。レッスン 5/23。

「Run」を押し、「Shell」タブで Book.objects.all() と入力します。すると、すべての本が <Book: Book object (1)> と表示され、見分けがつきません。Pythonは __str__ メソッドを使ってオブジェクトをテキストに変換します。すべてのモデルが持つこのメソッドは、IDだけを表示します。モデルには独自のメソッドを定義できます。映画サイトの Movie なら、タイトルと公開年を表示できます。

class Movie(models.Model):
    ...

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

すると、シェルには <Movie: Alien (1979)> と表示され、管理画面や {{ movie }} を表示するテンプレートにも同じように表示されます。__str__ はテキストを 返す 必要があります。テキストを出力するだけのメソッドは None を返すため、その場合は str() が TypeError を発生させます。

challenge icon

チャレンジ

簡単
  • 本のタイトルと著者が「Dune by Frank Herbert」のように表示されるようにします。

このレッスンの「Run」では、4冊の本が追加されます。「Run」を押して、「Shell」タブにBook.objects.all()と入力します。

自分で試してみよう

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)

モデルと管理サイトのすべてのレッスン

自分で練習してみよう: Djangoプレイグラウンド