Menu

Models and Database Basics

Models and Database Basics

Creating Models

A model is a Python class that inherits from django.db.models.Model. Each class attribute becomes a column in the database table.

The __str__ method controls how a model instance is displayed — in the admin, in the shell, and when you print it. Always define it. The inner Meta class lets you configure table-level options like default ordering and verbose names.

Database Migrations

Migrations are Django's way of tracking and applying changes to your database schema. Every time you create or modify a model, you generate a migration file and then apply it.

# Step 1 — generate the migration file

python manage.py makemigrations

# Step 2 — apply the migration to the database

python manage.py migrate

You can also see what SQL Django will run without actually running it:

python manage.py sqlmigrate courses 0001

Migrations are version control for your database schema. The generated files should be committed to Git — they let any developer on your team recreate the exact same database structure from scratch.

Introduction to Django ORM

The ORM is what makes working with databases in Django feel like working with Python. Here are the most important operations:

Queries are lazy — Django doesn't actually hit the database until you iterate over the queryset or explicitly evaluate it. This lets you chain filters together efficiently.