No account is required. Learn the material, try the examples, and mark it complete locally when you are ready to move on.
Tutorial 10 - Django Models and Migrations
Why this matters
Applications need to remember information.
A booking application remembers bookings. An inventory application remembers products. A CRM remembers customers.
Django models describe this data in Python.
1. A model
python
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=100)
price = models.DecimalField(
max_digits=10,
decimal_places=2,
)
class Booking(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
date = models.DateField()
confirmed = models.BooleanField(default=False)
3. The database connection
A relational database stores records in tables.
Your model:
python
class Product(models.Model):
name = ...
price = ...
corresponds conceptually to:
text
product table
id | name | price
---|----------|------
1 | Laptop | 50000
2 | Mouse | 1000
Django's ORM lets you work with these records using Python.
4. What is a migration?
Changing models.py does not automatically change the database.
Suppose you add:
python
description = models.TextField()
Your Python model now expects a new field.
The database also needs a structural change.
Migrations are Django's mechanism for recording and applying those changes.
5. Creating migrations
Run:
bash
python manage.py makemigrations
Django examines your models and creates a migration file.
You might see:
text
Migrations for 'main':
main/migrations/0002_add_description.py