Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 77 ยท Models and the ORM

Models and Fields

Learn how Django models map Python classes to database tables, with field types, field options, choices, Meta options, primary keys, table names and validation.

A model is a Python class that describes one kind of thing your application stores: a book, a customer, an order. Each model maps to one database table, each attribute that you declare as a field maps to a column, and each instance of the class represents one row. Models are the heart of Django, because almost everything else (forms, the admin, serializers, queries) is built on top of them.

You describe the data once, in Python, and Django generates the SQL for you. You never write CREATE TABLE by hand, and you can switch between SQLite, PostgreSQL, MySQL and others without changing the model code. This lesson covers the building blocks: fields, their options, choices, the Meta class, primary keys and table names. Creating the tables from your models is the job of migrations, and reading and writing rows is covered in QuerySets.

flowchart LR
    C["class Book(models.Model)"] --> T["Table library_book"]
    F1["title = CharField(...)"] --> K1["Column title"]
    F2["price = DecimalField(...)"] --> K2["Column price"]
    I["Book(title='Dune')"] --> R["One row"]

A model class becomes a table, a field becomes a column and an instance becomes a row.

Running models in the browser

A real project keeps models in models.py inside an app, and the migrate command creates the tables. The examples on this page run in your browser without any files, so they do three things differently:

  1. settings.configure(...) sets up Django with an in-memory SQLite database, where manage.py and settings.py would normally do it.
  2. Every model gets class Meta: app_label = "library", because the example has no installed app that would give the model a home. In a real app you do not write this.
  3. A small create_tables() helper uses the schema editor, the same low-level tool that migrations use, to create each table. It drops a table with the same name first, so you can press Run more than once.

The model classes themselves are exactly what you would put in models.py.

Defining a model

A model inherits from django.db.models.Model, and each field is a class attribute created from a field class. Here is a book model with several kinds of fields:

Python A model with many field types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Several things happened without you asking for them:

  • The books come back sorted by title because of ordering in Meta.
  • print(book) shows the title, since __str__ returns it. Without __str__ you would see Book object (1) everywhere, including in the admin, so always define it.
  • The second book has pages 0 and in_print True, the defaults. It has no published date, which is stored as NULL and read back as None.
  • Django added an id column automatically. pk and id are the same value here.

Common field types

Each field class decides three things: the column type in the database, how the value looks in Python, and which form widget and validation the field gets.

Field Python value Typical use
CharField(max_length=...) str Names, titles, short text. max_length is required.
TextField() str Long text such as descriptions or article bodies.
IntegerField, PositiveIntegerField, BigIntegerField int Counts, quantities, ids from other systems.
DecimalField(max_digits, decimal_places) Decimal Money. Never use floats for prices.
FloatField() float Measurements where tiny rounding errors are fine.
BooleanField() bool Flags such as is_active.
DateField, TimeField, DateTimeField date, time, datetime Dates and timestamps.
EmailField, URLField, SlugField str Text that is validated as an email, URL or slug.
UUIDField() uuid.UUID Hard-to-guess identifiers.
JSONField() dict, list, ... Flexible, schemaless data (see Raw SQL and database features).
FileField, ImageField FieldFile Uploaded files (see Static Files and Media).

Relationships (ForeignKey, ManyToManyField, OneToOneField) are fields too, and have their own lesson: Relationships.

Field options

Every field accepts a set of options that shape its behavior. These are the ones you will use daily:

Option Effect
null=True The database column may hold NULL.
blank=True Validation (forms, the admin, full_clean) accepts an empty value.
default=... Value used when none is given. Can be a callable, such as default=dict or default=timezone.now.
unique=True The database refuses duplicate values and creates an index.
choices=... Restricts valid values to a list and gives forms a dropdown.
db_index=True Creates an index to speed up lookups.
validators=[...] Extra validation functions.
verbose_name, help_text Human-friendly label and hint, used by forms and the admin.
editable=False Hides the field from forms and the admin.
db_column="..." Chooses the column name.

The most confused pair is null and blank. null is about the database; blank is about validation. For text fields, the Django convention is to use blank=True and no null, so "no value" is always the empty string and there are not two ways to say "nothing". For dates, numbers and other non-text fields, an optional value needs both null=True and blank=True.

Two more points are important. default must never be a mutable object like []; pass the callable list so every row gets a fresh one. And auto_now_add=True (set once, on creation) and auto_now=True (set on every save) are handy for timestamps, but they make the field read-only in forms.

Validation is separate from saving

Field options like max_length, blank, choices and validators are enforced by validation, which happens in forms, the admin, and when you call full_clean() on an instance. Calling save() does not run validation. The database only enforces what it knows about: NOT NULL, UNIQUE, foreign keys and check constraints. The next example shows the difference.

Python Field options and validation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

full_clean() collected an error for each bad field and put them in a dictionary: the blank title, the invalid slug, the rating below the minimum, a price with too many digits, and a format that is not one of the choices. The good instance passed, and its omitted fields received their defaults ('PB', an empty string for the blank-allowed subtitle, and None for the nullable rating).

The last two parts are the warning. The unique slug is protected by the database, so a duplicate raises IntegrityError. But a 30-character title was happily stored in a field declared max_length=20, because SQLite ignores varchar lengths and save() never validates. In real code, validation runs for you in forms and ModelForms (Django Forms); when you create objects from other sources, call full_clean() yourself.

Choices and TextChoices

When a field has a fixed set of valid values, define them once as an inner class based on models.TextChoices (or IntegerChoices). Each member has a stored value, a human-readable label, and a Python name, so you can write Book.Format.EBOOK instead of the magic string "EB". The earlier output shows all three views of the same member: Book.Format.EBOOK.label is E-book, its .value is EB, and Book.Format("PB").name is PAPERBACK. Django also adds a get_<field>_display() method that returns the label for the stored value, such as get_format_display().

Choices are not a database constraint. Anyone calling save() can still store "XX". Validation catches it in forms and in full_clean(), and you can add a CheckConstraint when the database must enforce it (see Custom Managers, QuerySets and Model Methods).

The Meta class

The inner class Meta holds options about the model as a whole rather than about one field. Frequently used options:

  • ordering = ["title"] sets the default order of query results (prefix a field with - for descending).
  • verbose_name and verbose_name_plural change the names shown in the admin.
  • db_table = "countries" overrides the table name.
  • indexes, constraints and unique_together describe indexes and rules over several columns.
  • abstract = True makes the model a base class that has no table of its own (see Model Inheritance).

Primary keys, table names and the SQL

Unless you declare a primary key, Django adds id = BigAutoField(primary_key=True) for you. To use your own natural key, set primary_key=True on a field, such as a country code. The default table name combines the app label and the lowercase model name: library_book. The next example inspects the metadata Django builds for two models and prints the SQL the schema editor would run to create them:

Python Model metadata and the generated SQL

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Model._meta is the model's introspection object: it knows every field, the table name and the primary key. In the output, Country uses its code as primary key and has no id, Tag got an automatic id, and nickname is stored in a column called nick. The SQL also reveals how Django maps field options to the database: unique=True became UNIQUE, null=True omitted NOT NULL, the positive big integer received a CHECK constraint, and the Meta.indexes entry produced a CREATE INDEX.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a Django model class correspond to in the database?

    A model maps to one table. Its fields become columns, and every instance of the model represents one row in that table.
  2. 2. What is the difference between null=True and blank=True?

    null is a database-level setting (the column can store NULL). blank only affects validation, such as forms and full_clean().
  3. 3. You call save() on an instance whose title is longer than max_length on SQLite. What happens?

    save() skips validation. SQLite does not enforce varchar lengths, so the long value is stored. Call full_clean() (or use a form) to validate first.
  4. 4. Which is the best way to define a field with a fixed set of valid values?

    TextChoices (or IntegerChoices) gives each member a value, label and name, works with choices=, and adds get_FOO_display().
  5. 5. If you do not declare a primary key on a model, what does Django do?

    Django automatically adds an id field (BigAutoField by default) as the primary key unless one of your fields sets primary_key=True.

Summary

  • A model is a class that inherits from models.Model; it maps to a table, its fields to columns and its instances to rows.
  • Pick the field class that matches your data (CharField, DecimalField for money, DateTimeField, and so on) and tune it with options such as default, unique, choices and validators.
  • null concerns the database and blank concerns validation; for text, prefer blank=True without null.
  • save() does not validate. Use forms or full_clean() for validation, and database constraints for rules that must always hold.
  • Use TextChoices for fixed value sets, __str__ for readable objects and Meta for ordering, names, indexes and constraints.
  • Without a declared primary key, Django adds an id; the default table name is <app_label>_<modelname>.

Models describe your schema, but the database does not know about them until you create the tables. That is the job of Migrations.