Django Models
A model is a Python class that describes one table in your database. Django creates the table for you.
The Database
A new project uses SQLite by default. The whole database is one file, db.sqlite3, so there is nothing to install. Later you can switch to PostgreSQL or MySQL by changing DATABASES in settings.py, without changing your models.
Your First Model
Edit courses/models.py:
Example
from django.db import models
class Course(models.Model):
name = models.CharField(max_length=100)
fee = models.PositiveIntegerField()
duration_months = models.PositiveSmallIntegerField(default=3)
is_online = models.BooleanField(default=False)
description = models.TextField(blank=True)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name- Each attribute becomes a column
- Django adds an
idcolumn (the primary key) automatically __str__decides how a course is shown in the admin and the shell
Common Field Types
| Field | Stores |
|---|---|
CharField(max_length=...) | Short text, like a name |
TextField() | Long text |
IntegerField() / PositiveIntegerField() | Whole numbers |
DecimalField(max_digits, decimal_places) | Exact decimals, like money |
BooleanField() | True or False |
DateField() / DateTimeField() | Dates and times |
EmailField() | An email address |
SlugField() | URL-friendly text |
ForeignKey(...) | A link to another model |
Useful options: default=..., blank=True (allowed empty in forms), null=True (allowed empty in the database), unique=True.
Migrations
Migrations turn your model changes into database changes. Run two commands:
Example
python manage.py makemigrations
python manage.py migrateMigrations for 'courses':
courses/migrations/0001_initial.py
+ Create model Course
Operations to perform:
Apply all migrations: admin, auth, contenttypes, courses, sessions
Running migrations:
Applying courses.0001_initial... OK| Command | What it does |
|---|---|
makemigrations | Writes a migration file describing your changes |
migrate | Applies all pending migrations to the database |
showmigrations | Lists migrations and whether they are applied |
Run both commands every time you add, remove or change a model field.
Relationships
A student joins one course; a course has many students. Use ForeignKey:
Example
class Student(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField(unique=True)
course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name="students")
joined = models.DateField(auto_now_add=True)
def __str__(self):
return f"{self.name} ({self.course})"on_delete=models.CASCADE means: if a course is deleted, delete its students too. Other options are PROTECT (block the delete) and SET_NULL (needs null=True).
| Relationship | Field | Example |
|---|---|---|
| Many to one | ForeignKey | Many students, one course |
| Many to many | ManyToManyField | Students and skills |
| One to one | OneToOneField | A user and a profile |
Trying Models in the Shell
Example
python manage.py shellExample
from courses.models import Course, Student
web = Course.objects.create(name="Web Development", fee=8000, duration_months=6)
Student.objects.create(name="Ali", email="ali@example.com", course=web)
print(web.students.count())
print(Student.objects.first())1 Ali (Web Development)
Exercise
Exercise
After adding a new field to a model, which two commands update the database?
