Skip to content
Kuza Ndoto Academy

Models

IntermediateChapter 4 · Page 12 of 234 min readUpdated 15 Nov 2026

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.

class Event(models.Model): title = CharField(...) venue = CharField(...) starts_at = DateTimeField() is_free = BooleanField(...) ... + id added automatically events_event table id title venue starts_at 2 Campus Hackathon ICT Lab 2 2026-11-28 3 Career Fair Main Hall 2026-12-02 each field becomes a column each Event object is one row (some columns not shown)
Figure 1. A model is a blueprint for a table. Example rows show two events; the date column also stores a time.

Common field types

FieldStoresExample
CharField(max_length=...)Short text; max_length is requiredTitle, venue, phone number
TextFieldLong text of any lengthEvent description
IntegerField / PositiveIntegerFieldWhole numbersCapacity, number of tickets
DecimalField(max_digits, decimal_places)Exact decimals; use for moneyTicket price in KES
FloatFieldApproximate decimalsGPS coordinates
BooleanFieldTrue / FalseIs the event free?
DateField / DateTimeFieldA date, or a date and timeWhen the event starts
EmailField, URLField, SlugFieldText with built-in validationContact email, website, URL slug
ImageField / FileFieldA path to an uploaded fileEvent poster
ForeignKey, ManyToManyFieldLinks to other modelsSee Model Relationships
Warning

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 store NULL (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_name and help_text: friendlier labels and hints in forms and the admin.
  • auto_now_add=True sets a date/time when the row is created; auto_now=True updates 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.)

Common mistake

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 Meta holds options for the whole model. ordering = ["starts_at"] sorts results by start time (use "-starts_at" for newest first). Other options include verbose_name_plural and constraints.
  • __str__ controls how an object appears in the admin, the shell and templates. Without it you'd see unhelpful text like Event object (1).
  • get_absolute_url() returns the object's own page. The admin uses it for a "View on site" button, and redirect(event) uses it too.
  • Custom methods and properties like is_upcoming keep 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.

Common mistake

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 id primary key automatically.
  • blank is about form validation; null is about the database.
  • Always define __str__, and consider Meta.ordering and get_absolute_url().
  • After changing a model, create and apply a migration.
Up next · Models & DatabasesMigrationsTurn models into database tables.
→

Tip: use the ← and → keys to move between pages.