Django: projects, apps and the ORM
Django is a "batteries included" framework: it comes with an ORM, migrations, an admin panel, authentication, forms, templates, security protections and much more. Instagram, Pinterest, Mozilla and The Washington Post built on it. This lesson covers how a Django project is organised and how its ORM turns Python classes into database tables.
Creating a project
On your computer:
pip install django
django-admin startproject mysite . # the project: settings, root URLs
python manage.py startapp shop # an app: one area of functionality
python manage.py runserver # http://127.0.0.1:8000That creates:
manage.py command-line tool for this project
mysite/
├── settings.py configuration: apps, database, security, time zone…
├── urls.py the root URL routes
├── asgi.py / wsgi.py entry points for production servers
shop/
├── models.py database tables, as classes
├── views.py functions that handle requests
├── admin.py admin panel registrations
├── apps.py
├── tests.py
└── migrations/ the history of database changesA project is the whole site; apps are reusable components inside it (shop, blog, accounts). You register an app by adding it to INSTALLED_APPS in settings.py.
In these editors, each
# file:line starts a new file of a small project, and the last file runs. The editor creates the settings for you (with an SQLite database, every folder that has amodels.pyas an installed app, andurls.pyas the URL configuration) and runs the migrations, just aspython manage.py migratewould.
Models
A model is a Python class that maps to a database table. Each attribute is a column:
- Every model gets an automatic
idprimary key. ForeignKeylinks to another model;on_delete=PROTECTrefuses to delete a category that still has products (CASCADEwould delete them too).DecimalFieldreturns exactDecimalvalues: never use floats for money.__str__controls how objects print, everywhere including the admin.
Common field types
| Field | Stores |
|---|---|
CharField(max_length=…) |
Short text |
TextField() |
Long text |
IntegerField, PositiveIntegerField, DecimalField, FloatField |
Numbers |
BooleanField(default=False) |
True/False |
DateField, DateTimeField(auto_now_add=True) |
Dates and times |
EmailField, URLField, SlugField, UUIDField |
Validated strings |
ForeignKey, OneToOneField, ManyToManyField |
Relationships |
JSONField |
JSON data |
Options available on most fields: null=True (allow NULL in the database), blank=True (allow empty in forms), default=…, unique=True, choices=…, db_index=True.
Migrations
When you change a model, Django doesn't touch the database until you create and apply a migration:
python manage.py makemigrations # writes shop/migrations/0001_initial.py
python manage.py migrate # applies it to the database
python manage.py showmigrations # what's applied
python manage.py sqlmigrate shop 0001 # the SQL it will runMigrations are Python files committed to Git, so every developer and every server gets exactly the same schema changes, in order.
Querying with the ORM
The ORM writes SQL for you. Model.objects is a manager; its methods return QuerySets, which are lazy (no query runs until you use the results) and chainable:
| Lookup | Means |
|---|---|
exact, iexact |
Equals (case-insensitive) |
contains, icontains |
Contains text |
startswith, endswith |
Text begins/ends with |
gt, gte, lt, lte |
Comparisons |
in |
One of a list: id__in=[1, 2, 3] |
isnull |
True or False |
range |
Between two values |
category__name |
Follow a relationship (a JOIN) |
Relationships and the N+1 problem
Accessing book.author for each book ran one extra query per book. select_related (for foreign keys) does a JOIN instead; prefetch_related (for reverse and many-to-many relations) loads them all in a second query. Watch for this in every list page.
The Django shell
On your computer, python manage.py shell opens Python with your project loaded (and models imported automatically since Django 5.2), which is the best place to experiment with queries.
Practice
- Add a
Reviewmodel (productforeign key,stars1–5,text) and print each product's average rating withannotate(Avg(...)). - Find all products whose name starts with "M" or that cost more than 30, ordered by price.
- Increase the stock of every Office product by 10 with a single
update()usingF().
1.What does python manage.py makemigrations do?
2.What does Product.objects.filter(price__lt=20) return?
3.Which method avoids one query per row when you access book.author?