Python Tutorial
Django Models
A model is a Python class that describes a database table. Django's ORM turns it into SQL and gives you a query API.
Define the Member Model
Open members/models.py:
from django.db import models
class Member(models.Model):
firstname = models.CharField(max_length=255)
lastname = models.CharField(max_length=255)
def __str__(self):
return f"{self.firstname} {self.lastname}"Django adds an id primary key automatically unless you define another one.
Common Field Types
| Field | Stores |
|---|---|
CharField | Short text (needs max_length) |
TextField | Long text |
IntegerField | Whole numbers |
DateField / DateTimeField | Dates |
BooleanField | True / False |
EmailField | Email string with validation |
ForeignKey | Link to another model |
Make and Run Migrations
Tell Django to turn the model into SQL, then apply it:
python manage.py makemigrations
python manage.py migratemakemigrations writes a file under members/migrations/. migrate runs that SQL against db.sqlite3 (and Django's own tables the first time).
Run python manage.py sqlmigrate members 0001 to preview the CREATE TABLE statement without applying it.
Inspect the Table
python manage.py dbshell
.tables
.schema members_member
.quitThe table name defaults to app_model in lowercase: members_member.
📘 Real-World Deep Dive
Knowing <strong>Django Models (Django)</strong> well is what turns Django from a curiosity into a daily tool — you'll reach for it in nearly every real project.
Real-Life Scenario
An end-to-end usage of Django Models that you'd actually see in a data pipeline or analytics notebook.
Real-Life Example
# core/models.py
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=120)
pages = models.PositiveIntegerField(default=0)
pub = models.DateField(null=True, blank=True)
class Meta:
ordering = ["-pub"]
indexes = [models.Index(fields=["author"])]
def __str__(self):
return self.titleExpected Output
(no output)Common mistakes
- Forgetting to call
.save()on a model instance after mutation silently persists nothing. - Reading every row with
Model.objects.all()on a 1 M-row table OOMs the worker — use.iterator()for streaming. - Queries inside loops produce N+1 problems — pull related rows with
select_related/prefetch_related. - Treating Django Models as a black box without reading the docs — the API has subtle defaults that bite when you scale.
🚀 Performance & Best Practices
- Add database indexes (
db_index=TrueorMeta.indexes) on columns used infilter. - Use
cache_pageon read-heavy views and setCONN_MAX_AGEto keep DB connections warm. - Generate migrations with
python manage.py makemigrations --dry-run --verbosity 3and review before committing. - When working with Django, prefer vectorised / batched operations over Python loops.
🧪 Try It Yourself
- Reproduce the snippet on a representative slice of your own data.
- Profile the snippet with
cProfileortimeitand find the single biggest improvement. - Generalise the snippet into a small, reusable function you can drop into future projects.