पाठ 11 / 26

Defining Models

Fields, relations, Meta.

Classes map to tables

Each models.Model subclass becomes a table; fields define columns (CharField, DecimalField, BooleanField, DateTimeField) and relations (ForeignKey, ManyToManyField, OneToOneField). on_delete decides what happens when the referenced row is deleted (CASCADE, PROTECT, SET_NULL). Meta sets ordering, indexes and constraints. Use DecimalField for money, unique constraints for natural keys, and related_name for readable reverse relations.

From classes to tables

Models describe data; migrations evolve the schema safely.

Four ideas: models, makemigrations, the SQL behind migrations, applying them.
Figure 4.1 — Models, migrations, SQL and migrate.

The catalog models

I ran this with Django 6.1.1 and Python 3.12 in a demo project (shopsite with a catalog app) using SQLite. Category has a unique name; Product references it with PROTECT, uses a decimal price, a default ordering and a composite index.

from django.db import models


class Category(models.Model):
    name = models.CharField(max_length=50, unique=True)

    def __str__(self):
        return self.name


class Product(models.Model):
    category = models.ForeignKey(Category, on_delete=models.PROTECT, related_name="products")
    name = models.CharField(max_length=100)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    in_stock = models.BooleanField(default=True)
    created = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["name"]
        indexes = [models.Index(fields=["category", "price"])]

    def __str__(self):
        return f"{self.name} ({self.price})"

Choose on_delete deliberately

PROTECT prevents accidental mass deletion; CASCADE is convenient but can remove far more data than expected.

त्वरित जाँच: Which field type should store prices?

  • IntegerField storing text
  • FloatField
  • CharField
  • DecimalField
Answer

DecimalField — Exact decimal arithmetic.