Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

DJ
Django & FastAPI
0/12 completed
Beginner
How Python web frameworks workYour first FastAPI appRequest bodies and Pydantic models
Intermediate
FastAPI with a databaseDependencies, routers and testingDjango: projects, apps and the ORMDjango views, URLs and templatesForms, the admin and class-based views
Advanced
APIs with Django REST frameworkAuthentication in Django and FastAPIBackground tasks and async
Pro
Deploying Python web apps
Tracks / Django & FastAPI / Intermediate

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:

bash
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:8000

That 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 changes

A 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 a models.py as an installed app, and urls.py as the URL configuration) and runs the migrations, just as python manage.py migrate would.

Models

A model is a Python class that maps to a database table. Each attribute is a column:

Python · editable
  • Every model gets an automatic id primary key.
  • ForeignKey links to another model; on_delete=PROTECT refuses to delete a category that still has products (CASCADE would delete them too).
  • DecimalField returns exact Decimal values: 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:

bash
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 run

Migrations 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:

Python · editable
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

Python · editable

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

  1. Add a Review model (product foreign key, stars 1–5, text) and print each product's average rating with annotate(Avg(...)).
  2. Find all products whose name starts with "M" or that cost more than 30, ordered by price.
  3. Increase the stock of every Office product by 10 with a single update() using F().
✎ Check your understanding

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?

← Dependencies, routers and testing