ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Django Tutorial• 9 min read

Django Models & The ORM Database Layer

Defining schemas in pure Python and generating automated database migrations

The Django Object-Relational Mapper (ORM) allows you to define database tables, columns, constraints, and relationships using clean Python classes without writing raw SQL.

Model Definitions and the Migration Workflow

Each model subclass inherits from django.db.models.Model.

Fields specify column types: CharField, TextField, IntegerField, DecimalField, DateTimeField, BooleanField.

Relationships: ForeignKey (one-to-many), ManyToManyField (many-to-many), OneToOneField (one-to-one).

python manage.py makemigrations: Inspects models and writes migration blueprint files.

python manage.py migrate: Executes SQL schema changes against your target database.

Course and Enrollment Models (models.py)
from django.db import models
from django.contrib.auth.models import User

class Category(models.Model):
    title = models.CharField(max_length=100, unique=True)
    slug = models.SlugField(max_length=120, unique=True)

    def __str__(self):
        return self.title

class Course(models.Model):
    category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='courses')
    title = models.CharField(max_length=200)
    description = models.TextField()
    price = models.DecimalField(max_digits=6, decimal_places=2, default=0.00)
    is_published = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.title} - $" + str(self.price)
on_delete=models.CASCADE guarantees child courses delete if their parent category is removed.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which command generates new migration files based on detected changes in models.py?