Tables
Data lives in tables: a row is one record (a product), a column is one property (name, price).
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.
Variables in Python live only while the program runs. A database keeps data on disk and can find it quickly.
Data lives in tables: a row is one record (a product), a column is one property (name, price).
Every row has a unique number, id. You can use it to find, change or delete the record.
The database query language: SELECT reads, INSERT adds, UPDATE changes, DELETE removes.
A layer that turns Python classes into tables and method calls into SQL queries.
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.
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.
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.
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
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
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.
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=100)
price = models.PositiveIntegerField()
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()
| 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() |
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.
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
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.
Code with an ORM barely changes when you switch databases: only the connection settings change.
| 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.
Four questions on this section. An explanation appears after you answer.
Examples checked on Python 3.13, SQLite and Django 6.1.3, .
In the first project you will connect SQLite to Flask and work with a model in Django.