Skip to content

Adding Model Methods

A model is a regular Python class, so we can add methods to it.

String Representation

__str__ is the method Python calls to turn an object into a string, for print() and str().

models.Model provides a default __str__ that shows an animal as Animal object (1), with its id. That default is used in the shell, the admin, and every dropdown. Let's use the animal's name instead:

animals/models.py
    intake_date = models.DateField(default=date.today)

    def __str__(self):
        return self.name

An Age Label

We store an animal's birth date, but a visitor browsing the site wants to know whether the animal is young or grown. We'll add an age_label() method that turns the birth date into a label:

  • Under a year old: "Puppy", "Kitten", or "Bunny", depending on the species.
  • A year old or more: "Adult".

age_label() isn't a field, so it doesn't add a column to the table. It computes the label from the birth date each time it's called, so the label stays right as the animal gets older. The templates and the API can both call it.

age_label() comes with this chapter's exercise branch.