How a website stores data

Users, tasks, products, comments: everything that must survive closing the tab is kept in a database. We will look at SQL using SQLite and show how the Django ORM does the same.

Just starting out? First go through the “From scratch” lessons, and look up unfamiliar words in the glossary.

Rows of card catalogue drawers at the Library of Congress

Why a server needs a database

Variables in Python live only while the program runs. A database keeps data on disk and can find it quickly.

Tables

Data lives in tables: a row is one record (a product), a column is one property (name, price).

Primary key

Every row has a unique number, id. You can use it to find, change or delete the record.

SQL

The database query language: SELECT reads, INSERT adds, UPDATE changes, DELETE removes.

ORM

A layer that turns Python classes into tables and method calls into SQL queries.

SQL in practice: the sqlite3 module

SQLite is a database in a single file. It is built into Python and needs no server, so it is the best option for learning projects. Save the code to a file and run it: it creates shop.db.

shop.py
import sqlite3

conn = sqlite3.connect("shop.db")

conn.execute("""
    CREATE TABLE IF NOT EXISTS products (
        id INTEGER PRIMARY KEY,
        name TEXT NOT NULL,
        price INTEGER NOT NULL
    )
""")

conn.execute("INSERT INTO products (name, price) VALUES (?, ?)", ("Notebook", 350))
conn.execute("INSERT INTO products (name, price) VALUES (?, ?)", ("Pen", 150))
conn.commit()

for name, price in conn.execute("SELECT name, price FROM products WHERE price < ?", (300,)):
    print(name, price)  # Pen 150

conn.execute("UPDATE products SET price = ? WHERE name = ?", (400, "Notebook"))
conn.execute("DELETE FROM products WHERE name = ?", ("Pen",))
conn.commit()

print(conn.execute("SELECT name, price FROM products").fetchall())  # [('Notebook', 400)]
conn.close()

Do not forget commit(). Changes (INSERT, UPDATE, DELETE) reach the file only after conn.commit(). Without it the data is lost when the connection closes.

The main rule: parameters instead of f-strings

If you put the user's text straight into SQL, the user can change the query itself. This is called SQL injection, one of the most common vulnerabilities of websites.

Dangerous: an f-string
name = "' OR '1'='1"  # a user could type this

rows = conn.execute(
    f"SELECT * FROM products WHERE name = '{name}'"
).fetchall()
# returns ALL products: the condition is now always true
Safe: the ? parameter
name = "' OR '1'='1"

rows = conn.execute(
    "SELECT * FROM products WHERE name = ?", (name,)
).fetchall()
# returns an empty list: there is no product with that name

The same with the Django ORM

In Django a table is described by a model class, and queries are written as Python methods. Django builds the SQL itself and always passes values as parameters, so injection is not a worry here.

shop/models.py
from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=100)
    price = models.PositiveIntegerField()
python manage.py shell
from shop.models import Product

Product.objects.create(name="Notebook", price=350)
Product.objects.create(name="Pen", price=150)

print(Product.objects.filter(price__lt=300).values_list("name", flat=True))  # <QuerySet ['Pen']>
Product.objects.filter(name="Notebook").update(price=400)
Product.objects.filter(name="Pen").delete()
The same operations in SQL and in the Django ORM
Action SQL ORM Django
Add INSERT INTO products (name, price) VALUES (?, ?) Product.objects.create(name=…, price=…)
Find by condition SELECT … FROM products WHERE price < 300 Product.objects.filter(price__lt=300)
Change UPDATE products SET price = 400 WHERE … Product.objects.filter(…).update(price=400)
Delete DELETE FROM products WHERE … Product.objects.filter(…).delete()

Migrations: how a model becomes a table

A migration is a file with instructions for how to change the database. Django creates it from changes in the models and then applies it. This way the database structure always matches the code and is easy to recreate on another computer.

Terminal
python manage.py makemigrations   # create a migration from the models
python manage.py migrate          # apply it to the database
python manage.py sqlmigrate shop 0001   # show the migration's SQL
The SQL Django generated
CREATE TABLE "shop_product" (
    "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
    "name" varchar(100) NOT NULL,
    "price" integer unsigned NOT NULL CHECK ("price" >= 0)
);

Note that PositiveIntegerField became the check CHECK ("price" >= 0): the database itself will not save a negative price. The output was produced by the sqlmigrate command on Django 6.1 and SQLite.

Which database to choose

Code with an ORM barely changes when you switch databases: only the connection settings change.

Popular databases for Python projects
Database When to use Features
SQLite Learning projects, prototypes, small sites One file, built into Python, the default database in Django
PostgreSQL Real projects with users A separate server, reliable under concurrent requests
MySQL / MariaDB When your hosting provides it A separate server, common on hosting

Flask has no ORM of its own. You can write SQL through sqlite3, as in the second step of the Flask project, or add the Flask-SQLAlchemy extension.

Test yourself

Four questions on this section. An explanation appears after you answer.

1. Which SQL command changes existing records?
2. How do you safely put user input into an sqlite3 query?
3. You added a field to a Django model. What must you do to change the table?
4. Why might changes in sqlite3 not be saved?

Sources

Examples checked on Python 3.13, SQLite and Django 6.1.3, .

Try it in practice

In the first project you will connect SQLite to Flask and work with a model in Django.