Django Model Basics
Django comes with an Object-Relational Mapper (ORM).
An ORM lets us work with database rows as Python objects: a query returns instances of a class, and saving an instance writes a row.
The Animal Model
We need to keep track of the rescue's animals, so our first model is Animal.
A model is a class that describes one database table. Open animals/models.py and replace it with:
from django.db import models
class Animal(models.Model):
name = models.CharField(max_length=100)
Our class subclasses models.Model, and each field becomes a column in the table.
CharField is a string column with a maximum length. In Postgres, max_length=100 makes it a varchar(100) column.
Note
We didn't define a primary key. Django adds an auto-incrementing id field to every model.
Optional Fields
We need to know how old each animal is, so we'll store its birth date. When a stray arrives at the adoption center, we won't know its exact date of birth, so we'll enter an estimate:
class Animal(models.Model):
name = models.CharField(max_length=100)
birth_date = models.DateField()
A field is required unless we say otherwise. We may not know an animal's breed when it arrives, or have a write-up for it yet, so we'll add both as optional text fields:
breed = models.CharField(max_length=100, blank=True)
birth_date = models.DateField()
description = models.TextField(blank=True)
With blank=True, the field can be left empty, and it's saved as an empty string, not NULL. A field that isn't text, such as a date, has no empty string, so making it optional takes null=True as well.
TextField is text with no length limit, so it needs no max_length. Postgres stores it as a text column.
Default Values
We need to keep track of when the animal entered the system, so we'll set an intake date and default it to today.
We add intake_date after the other fields, and import date at the top of animals/models.py:
from datetime import date
from django.db import models
class Animal(models.Model):
name = models.CharField(max_length=100)
breed = models.CharField(max_length=100, blank=True)
birth_date = models.DateField()
description = models.TextField(blank=True)
intake_date = models.DateField(default=date.today)
default takes a value or a function. With default=date.today, Django calls the function to set the default when a new Animal is created.
Warning
With parentheses, date.today() would run once, when the module is imported, and every animal would get the date the server started.