Django Models
A model is a Python class that describes one database table. Each class attribute that is a Field becomes a column, each instance of the class is one row, and Django's ORM writes the SQL for you. Models are the single, definitive source of truth about your data.
# books/models.py
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=100)
published = models.DateField()
pages = models.PositiveIntegerField(default=0)Every model automatically gets an auto-incrementing primary key called id (also available as pk) unless you define your own.
Defining a model and creating its table
In the playground the model needs app_label and its table is created with the schema editor (in a project, migrations do this — see the next lesson). The _meta API shows what Django knows about the model:
import django
from django.conf import settings
settings.configure(DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}})
django.setup()
from django.db import models, connection
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=100)
pages = models.PositiveIntegerField(default=0)
in_stock = models.BooleanField(default=True)
class Meta:
app_label = "demo"
with connection.schema_editor() as editor:
editor.create_model(Book)
print("Table:", Book._meta.db_table)
for field in Book._meta.get_fields():
print(f" {field.name:<9} {field.get_internal_type()}")Table: demo_book
id AutoField
title CharField
author CharField
pages PositiveIntegerField
in_stock BooleanField
Common field types
| Field | Stores | Notes |
|---|---|---|
CharField(max_length=…) |
short text | max_length is required |
TextField() |
long text | no length limit |
IntegerField() / PositiveIntegerField() |
whole numbers | |
DecimalField(max_digits, decimal_places) |
exact decimals (money) | returns decimal.Decimal |
FloatField() |
floating point | |
BooleanField() |
True / False |
|
DateField() / DateTimeField() |
dates / timestamps | auto_now_add=True sets on creation |
EmailField(), URLField(), SlugField() |
validated text | |
ForeignKey, ManyToManyField, OneToOneField |
relationships | covered later |
Field options
Options work with almost every field type:
| Option | Effect |
|---|---|
null=True |
the column may store NULL in the database |
blank=True |
forms/validation allow an empty value |
default=… |
value used when none is given |
unique=True |
no two rows may share the value |
choices=[…] |
restrict to a fixed set of values |
verbose_name="…" |
human-friendly label (forms, admin) |
help_text="…" |
extra explanation shown in forms |
db_index=True |
create an index on the column |
Tip: For text fields, prefer
blank=Truewith the default empty string overnull=True. Otherwise "no value" has two representations:""andNULL.
Methods, __str__ and Meta
Models are ordinary classes, so you can add methods and properties. __str__ controls how an object is shown (in the shell, the admin and templates). The inner Meta class holds model-level options such as default ordering and the human-readable name.
import django
from django.conf import settings
settings.configure(DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}})
django.setup()
from django.db import models, connection
class Book(models.Model):
class Format(models.TextChoices):
PAPERBACK = "PB", "Paperback"
HARDCOVER = "HC", "Hardcover"
EBOOK = "EB", "E-book"
title = models.CharField(max_length=200)
pages = models.PositiveIntegerField()
format = models.CharField(max_length=2, choices=Format.choices, default=Format.PAPERBACK)
class Meta:
app_label = "demo"
ordering = ["title"]
verbose_name_plural = "library books"
def __str__(self):
return f"{self.title} ({self.pages} pages)"
@property
def is_long(self):
return self.pages > 500
with connection.schema_editor() as editor:
editor.create_model(Book)
Book.objects.create(title="War and Peace", pages=1225, format=Book.Format.HARDCOVER)
Book.objects.create(title="Animal Farm", pages=112)
for book in Book.objects.all(): # sorted by Meta.ordering
print(book, "| long:", book.is_long, "|", book.get_format_display())
print(Book._meta.verbose_name, "/", Book._meta.verbose_name_plural)Animal Farm (112 pages) | long: False | Paperback
War and Peace (1225 pages) | long: True | Hardcover
book / library books
For each field with choices, Django adds a get_<field>_display() method that returns the human label.
The SQL behind a model
Curious what Django sends to the database? The schema editor can collect the SQL instead of running it:
import django
from django.conf import settings
settings.configure(DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}})
django.setup()
from django.db import models, connection
class Member(models.Model):
email = models.EmailField(unique=True)
nickname = models.CharField(max_length=30, blank=True)
score = models.DecimalField(max_digits=5, decimal_places=1, null=True)
class Meta:
app_label = "demo"
with connection.schema_editor(collect_sql=True) as editor:
editor.create_model(Member)
for sql in editor.collected_sql:
print(sql)CREATE TABLE "demo_member" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "email" varchar(254) NOT NULL UNIQUE, "nickname" varchar(30) NOT NULL, "score" decimal NULL);
Notice how null=True produced NULL, while blank=True did not change the column at all — blank only affects validation.
Validating an instance
Saving doesn't validate fields for you (SQLite, for instance, doesn't enforce max_length). Call full_clean() — forms do this automatically — to check every field:
import django
from django.conf import settings
settings.configure()
django.setup()
from django.db import models
from django.core.exceptions import ValidationError
class Member(models.Model):
email = models.EmailField()
nickname = models.CharField(max_length=5)
class Meta:
app_label = "demo"
m = Member(email="not-an-email", nickname="much-too-long")
try:
m.full_clean()
except ValidationError as e:
for field, messages in e.message_dict.items():
print(field, "->", messages[0])email -> Enter a valid email address.
nickname -> Ensure this value has at most 5 characters (it has 13).
Test yourself
Which field type requires a max_length argument?
- TextField
- CharField
- IntegerField
- BooleanField
What is the difference between null=True and blank=True?
- They are identical
nullaffects the database column;blankaffects validationblankaffects the database;nullaffects formsnullis only for numbers
What does get_format_display() return for a field with choices?
- The stored value
- The human-readable label
- All choices
- The field name