Models
A model is a Python class that describes one kind of data your site stores, such as an event, a student or a payment. Django turns each model into a database table, and each instance of the model into a row, so you can work with data using Python instead of SQL.
Your first model
Models live in an app's models.py and inherit from django.db.models.Model. Each class attribute that is a field becomes a column in the table.
events/models.py
from django.db import models
from django.urls import reverse
from django.utils import timezone
class Event(models.Model):
title = models.CharField(max_length=200)
description = models.TextField(blank=True)
venue = models.CharField(max_length=100)
starts_at = models.DateTimeField()
is_free = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ["starts_at"]
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("events:event_detail", args=[self.pk])
@property
def is_upcoming(self):
return self.starts_at >= timezone.now()
From this class Django will create a table called events_event (app name, underscore, model name in lowercase). You don't have to define an ID: Django adds an auto-incrementing primary key called id (also available as pk). Its type comes from DEFAULT_AUTO_FIELD in settings, which new projects set to BigAutoField.
The model doesn't affect the database yet. You'll create the table on the Migrations page.
Common field types
| Field | Stores | Example |
|---|---|---|
CharField(max_length=...) | Short text; max_length is required | Title, venue, phone number |
TextField | Long text of any length | Event description |
IntegerField / PositiveIntegerField | Whole numbers | Capacity, number of tickets |
DecimalField(max_digits, decimal_places) | Exact decimals; use for money | Ticket price in KES |
FloatField | Approximate decimals | GPS coordinates |
BooleanField | True / False | Is the event free? |
DateField / DateTimeField | A date, or a date and time | When the event starts |
EmailField, URLField, SlugField | Text with built-in validation | Contact email, website, URL slug |
ImageField / FileField | A path to an uploaded file | Event poster |
ForeignKey, ManyToManyField | Links to other models | See Model Relationships |
Don't store money in a FloatField. Floats are approximate, so 0.1 + 0.2 is not exactly 0.3. Use DecimalField(max_digits=10, decimal_places=2) for prices and balances.
Field options
Options passed to a field fine-tune how it behaves:
default=...: the value used when none is given, e.g.default=True.blank=True: the field may be left empty in forms (a validation rule).null=True: the database may storeNULL(a database rule).unique=True: no two rows may share this value.choices=...: limit the value to a fixed list, shown as a drop-down in forms.verbose_nameandhelp_text: friendlier labels and hints in forms and the admin.auto_now_add=Truesets a date/time when the row is created;auto_now=Trueupdates it on every save.
Here's how choices looks using Django's TextChoices helper:
class Event(models.Model):
class Kind(models.TextChoices):
SOCIAL = "social", "Social"
ACADEMIC = "academic", "Academic"
SPORTS = "sports", "Sports"
kind = models.CharField(max_length=10, choices=Kind, default=Kind.SOCIAL)
The first value ("social") is stored in the database; the second ("Social") is the human-readable label. In a template, {{ event.get_kind_display }} prints the label. (This is just an illustration; the rest of the series doesn't add a kind field.)
Adding null=True to text fields. For CharField and TextField, Django's convention is to store "no value" as an empty string, so use blank=True alone. Adding null=True as well gives you two different kinds of "empty" to check for.
Meta, __str__ and methods
class Metaholds options for the whole model.ordering = ["starts_at"]sorts results by start time (use"-starts_at"for newest first). Other options includeverbose_name_pluralandconstraints.__str__controls how an object appears in the admin, the shell and templates. Without it you'd see unhelpful text likeEvent object (1).get_absolute_url()returns the object's own page. The admin uses it for a "View on site" button, andredirect(event)uses it too.- Custom methods and properties like
is_upcomingkeep data rules in one place. A template can use{% if event.is_upcoming %}.
This is the "fat models" idea: put logic about your data in the model, not scattered across views and templates.
How the model maps to SQL
For the curious, this is roughly the table Django will create in SQLite:
CREATE TABLE "events_event" (
"id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
"title" varchar(200) NOT NULL,
"description" text NOT NULL,
"venue" varchar(100) NOT NULL,
"starts_at" datetime NOT NULL,
"is_free" bool NOT NULL,
"created_at" datetime NOT NULL
);
You never write this yourself. Change the Python class, and migrations update the table to match, whether you use SQLite on your laptop or PostgreSQL in production.
Leaving out max_length on a CharField. Django refuses to run and reports fields.E120: CharFields must define a 'max_length' attribute.
Key points
- A model is a class in
models.py; each field becomes a column and each instance a row. - Django adds an
idprimary key automatically. blankis about form validation;nullis about the database.- Always define
__str__, and considerMeta.orderingandget_absolute_url(). - After changing a model, create and apply a migration.
Tip: use the ← and → keys to move between pages.
