Django Models

Django models describe your database tables as Python classes, and migrations turn those class definitions into real schema changes.

Defining a Model

A model is a Python class that subclasses django.db.models.Model. Each class attribute is a Field instance that maps to a database column, and Django uses the class as a whole to generate the table's schema.

Example

from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=200)
    price = models.DecimalField(max_digits=8, decimal_places=2)
    in_stock = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

Common Field Types

  • CharField(max_length=...) - short text like names or titles
  • TextField() - long, unbounded text such as descriptions
  • IntegerField() / DecimalField() - whole numbers or precise decimals like prices
  • BooleanField(default=...) - true/false flags
  • DateTimeField(auto_now_add=True) - a timestamp set once when the row is created
  • ForeignKey(Model, on_delete=...) - a many-to-one relationship to another model

Example

class Review(models.Model):
    product = models.ForeignKey(
        Product,
        on_delete=models.CASCADE,
        related_name='reviews',
    )
    rating = models.IntegerField()
    comment = models.TextField(blank=True)

    def __str__(self):
        return f'{self.rating} stars for {self.product.name}'
FieldTypical Use
CharFieldShort fixed-length text: names, titles, slugs
TextFieldLong free-form text: descriptions, comments
DecimalFieldExact decimal numbers: prices, money
BooleanFieldTrue/false flags: is_active, in_stock
ForeignKeyOne-to-many relationship to another model

Migrations

Migrations are how Django keeps your database schema in sync with your models. makemigrations inspects your model classes, compares them to the last known state, and writes a migration file describing the difference. migrate then applies any pending migration files to the actual database.

Example

# Generate migration files from model changes
python manage.py makemigrations

# Apply pending migrations to the database
python manage.py migrate
Note: Add a __str__ method to every model. It's what shows up in the Django admin, the interactive shell, and error messages instead of an unhelpful 'Product object (1)'.
Note: Migration files in <app>/migrations/ are ordinary Python and belong in version control. When you pull a teammate's changes, run migrate to bring your local database schema up to date with theirs.

Exercise: Django Models

What must a Django model class inherit from?