In one sentence
With Oxyde, a Python ORM, we learn to ask the database only for the data we need: filter it, sort it, connect it to the author and count it. This means getting back the right rows, already sorted and counted, instead of taking everything and fixing it by hand in the program.
Where we left off
In part 1 we created a virtual environment, installed Oxyde 0.9.0, and described the tables authors and posts with two models, that is, two Python classes that represent the tables. Then we created the database blog.db with migrations, that is, the instructions that create the tables, and the first program saved 2 authors and 3 articles. This part continues the same project: we start from that data and use it to ask more and more precise questions.
What we’ll do in this part with Oxyde
The goal is to learn how to ask the database only for the data we need. We filter and exclude rows, sort them, and split them into pages. We compare numbers and text, follow the link between an article and its author, and calculate counts, sums and averages. At the end we will have these results:
- A list of articles that is filtered, sorted and split into pages.
- Searches on numbers and text, with lookups and with a search in the titles.
- Articles searched by the author’s data, and the author loaded together with each article.
- Counts, sums, averages, maximums and minimums, also separated by author.
- An OR search done correctly with
Qexpressions, after we have seen the error caused by twofilter()calls in a row.
What you need
You need the project from part 1: the environment with Oxyde installed and the database blog.db already created with its tables. You do not need keys or accounts.
Step by step
Step 2.1: We add one author and five articles
To test filters and counts we need more data, so we start from the database of part 1, which contains 2 authors and 3 articles, and we add the author Carla Verdi with five articles. First we get Alice and Bruno with get(), which returns exactly one row, searching them by email. Then we create the Post objects in a list and save them all together with bulk_create(). The file stampa.py contains a small function, mostra, which we will use throughout this part to print the articles always in the same format. This time the connection is opened with async with db.connect(...) and it closes by itself at the end of the block.
File stampa.py:
def mostra(etichetta, articoli):
"""Print a list of posts, one per line, always in the same format."""
print(f"--- {etichetta} ({len(articoli)}) ---")
for post in articoli:
stato = "pubblicato" if post.published else "bozza"
print(f"{post.id}: {post.title} | autore {post.author_id} | {stato} | {post.views} letture")
File aggiungi_dati.py:
import asyncio
from oxyde import db
from models import Author, Post
from oxyde_config import DATABASES
from stampa import mostra
async def main():
async with db.connect(DATABASES["default"]):
print(f"Prima: {await Author.objects.count()} autori, {await Post.objects.count()} articoli")
alice = await Author.objects.get(email="alice@example.com")
bruno = await Author.objects.get(email="bruno@example.com")
carla = await Author.objects.create(name="Carla Verdi", email="carla@example.com")
nuovi = [
Post(title="Filtri e lookup in Oxyde", content="filter, exclude e lookup.",
published=True, views=300, author_id=bruno.id),
Post(title="Relazioni tra tabelle", content="Chiavi esterne e join.",
published=True, views=80, author_id=bruno.id),
Post(title="Python asincrono per tutti", content="async e await.",
published=True, views=210, author_id=carla.id),
Post(title="Bozza: aggregazioni", content="Da scrivere.", author_id=carla.id),
Post(title="Appunti su SQLite", content="Un database in un file.",
views=15, author_id=alice.id),
]
await Post.objects.bulk_create(nuovi)
print(f"Dopo: {await Author.objects.count()} autori, {await Post.objects.count()} articoli")
mostra("Tutti gli articoli, in ordine di id", await Post.objects.order_by("id").all())
if __name__ == "__main__":
asyncio.run(main())
python aggiungi_dati.py
Output:
Prima: 2 autori, 3 articoli
Dopo: 3 autori, 8 articoli
--- Tutti gli articoli, in ordine di id (8) ---
1: Primi passi con Oxyde | autore 1 | pubblicato | 120 letture
2: Le migrazioni spiegate bene | autore 1 | pubblicato | 45 letture
3: Bozza: idee sparse | autore 2 | bozza | 0 letture
4: Filtri e lookup in Oxyde | autore 2 | pubblicato | 300 letture
5: Relazioni tra tabelle | autore 2 | pubblicato | 80 letture
6: Python asincrono per tutti | autore 3 | pubblicato | 210 letture
7: Bozza: aggregazioni | autore 3 | bozza | 0 letture
8: Appunti su SQLite | autore 1 | bozza | 15 letture
The program prints Prima: 2 autori, 3 articoli and then Dopo: 3 autori, 8 articoli, followed by the list of all the articles, with ids from 1 to 8. If you see these numbers, the new data has entered the database.
Step 2.2: We build a query without running it
Post.objects is the starting point of every query in this Python ORM. Methods such as filter() and order_by() do not query the database: they build the query one piece at a time and return a new one, of type Query, while the query only runs when you call a final method such as all(). The method sql() shows the SQL that will be run and, separately, the values that replace the placeholders $1, $2 and so on. To keep one line short, we print only the part of the SQL from WHERE onward. Queries never change: order_by() created a new query, and the starting one stayed without sorting.
File query_builder.py:
import asyncio
from oxyde import db
from models import Post
from oxyde_config import DATABASES
from stampa import mostra
async def main():
async with db.connect(DATABASES["default"]):
pubblicati = Post.objects.filter(published=True)
print("tipo dell'oggetto:", type(pubblicati).__name__)
dal_piu_letto = pubblicati.order_by("-views")
sql, parametri = dal_piu_letto.sql()
print("SQL:", sql[sql.index("WHERE"):])
print("parametri:", parametri)
sql_di_partenza, _ = pubblicati.sql()
print("la query di partenza contiene ORDER BY?", "ORDER BY" in sql_di_partenza)
mostra("Pubblicati, dal più letto", await dal_piu_letto.all())
if __name__ == "__main__":
asyncio.run(main())
python query_builder.py
Output:
tipo dell'oggetto: Query
SQL: WHERE "published" = $1 ORDER BY "views" DESC
parametri: [True]
la query di partenza contiene ORDER BY? False
--- Pubblicati, dal più letto (5) ---
4: Filtri e lookup in Oxyde | autore 2 | pubblicato | 300 letture
6: Python asincrono per tutti | autore 3 | pubblicato | 210 letture
1: Primi passi con Oxyde | autore 1 | pubblicato | 120 letture
5: Relazioni tra tabelle | autore 2 | pubblicato | 80 letture
2: Le migrazioni spiegate bene | autore 1 | pubblicato | 45 letture
You see the object’s type, Query, and the SQL line with WHERE "published" = $1 ORDER BY "views" DESC, followed by the parameter [True]. The last line printed says that the starting query does not contain ORDER BY: the sorting stayed in the new query, and this confirms that the starting query did not change.
Step 2.3: We filter and exclude with filter() and exclude()
filter() keeps only the rows that meet the conditions, while exclude() removes the rows that meet them. Several conditions in the same filter(), separated by commas, must all be true together. The two methods can be chained: in the last example we keep the published articles and remove Bruno’s. Every list has an explicit order_by("id"), because without sorting the database decides the order of the rows.
File filtri.py:
import asyncio
from oxyde import db
from models import Author, Post
from oxyde_config import DATABASES
from stampa import mostra
async def main():
async with db.connect(DATABASES["default"]):
bruno = await Author.objects.get(email="bruno@example.com")
mostra("Pubblicati", await Post.objects.filter(published=True).order_by("id").all())
mostra("Bozze (exclude)", await Post.objects.exclude(published=True).order_by("id").all())
mostra(
"Di Bruno e pubblicati",
await Post.objects.filter(author_id=bruno.id, published=True).order_by("id").all(),
)
mostra(
"Pubblicati, tranne quelli di Bruno",
await Post.objects.filter(published=True).exclude(author_id=bruno.id).order_by("id").all(),
)
if __name__ == "__main__":
asyncio.run(main())
python filtri.py
Output:
--- Pubblicati (5) ---
1: Primi passi con Oxyde | autore 1 | pubblicato | 120 letture
2: Le migrazioni spiegate bene | autore 1 | pubblicato | 45 letture
4: Filtri e lookup in Oxyde | autore 2 | pubblicato | 300 letture
5: Relazioni tra tabelle | autore 2 | pubblicato | 80 letture
6: Python asincrono per tutti | autore 3 | pubblicato | 210 letture
--- Bozze (exclude) (3) ---
3: Bozza: idee sparse | autore 2 | bozza | 0 letture
7: Bozza: aggregazioni | autore 3 | bozza | 0 letture
8: Appunti su SQLite | autore 1 | bozza | 15 letture
--- Di Bruno e pubblicati (2) ---
4: Filtri e lookup in Oxyde | autore 2 | pubblicato | 300 letture
5: Relazioni tra tabelle | autore 2 | pubblicato | 80 letture
--- Pubblicati, tranne quelli di Bruno (3) ---
1: Primi passi con Oxyde | autore 1 | pubblicato | 120 letture
2: Le migrazioni spiegate bene | autore 1 | pubblicato | 45 letture
6: Python asincrono per tutti | autore 3 | pubblicato | 210 letture
Each list has the number of rows in brackets in its title. The list “Bozze (exclude)” contains 3 rows, and the last list, published articles except Bruno’s, contains 3: they are the published articles with ids 1, 2 and 6, so Bruno’s (ids 4 and 5) are not there.
Step 2.4: We ask for one row, or a yes or no
We do not always need a list. get() returns exactly one row, while get_or_none() returns None, the Python value that means “no value”, if the row does not exist, instead of an error: we will see the errors of get() in part 3. first() takes the first row of the query, so it must be used after an order_by(). exists() answers only true or false, and count() returns the number of rows: in both cases the database does the calculation.
File uno_solo.py:
import asyncio
from oxyde import db
from models import Author, Post
from oxyde_config import DATABASES
async def main():
async with db.connect(DATABASES["default"]):
post = await Post.objects.get(id=4)
print("get(id=4):", post.title)
print("get_or_none(id=99):", await Post.objects.get_or_none(id=99))
piu_letto = await Post.objects.order_by("-views").first()
print("il più letto:", piu_letto.title, "con", piu_letto.views, "letture")
carla = await Author.objects.get(email="carla@example.com")
print("Carla ha bozze?", await Post.objects.filter(author_id=carla.id, published=False).exists())
print("articoli pubblicati:", await Post.objects.filter(published=True).count())
if __name__ == "__main__":
asyncio.run(main())
python uno_solo.py
Output:
get(id=4): Filtri e lookup in Oxyde
get_or_none(id=99): None
il più letto: Filtri e lookup in Oxyde con 300 letture
Carla ha bozze? True
articoli pubblicati: 5
The line get(id=4) returns the article with id 4, while get_or_none(id=99) returns None, because there is no article with id 99. The last lines answer with a yes or a no, or with a number, such as Carla ha bozze? True and articoli pubblicati: 5.
Step 2.5: We sort and split into pages
order_by("-views") sorts from the most read to the least read: the minus sign in front of the name means descending order. You can give several fields: with order_by("-views", "id"), if the views are equal, the id decides. limit(3) keeps only the first three rows. To split the results into pages you add offset(), which skips the first rows: page n of 3 articles skips (n - 1) * 3 rows. Here we also use values_list("title", flat=True), which returns only the titles instead of the complete objects.
File ordinamento.py:
import asyncio
from oxyde import db
from models import Post
from oxyde_config import DATABASES
from stampa import mostra
async def main():
async with db.connect(DATABASES["default"]):
mostra("I tre più letti", await Post.objects.order_by("-views", "id").limit(3).all())
per_pagina = 3
for pagina in (1, 2, 3):
titoli = await (
Post.objects.order_by("id")
.offset((pagina - 1) * per_pagina)
.limit(per_pagina)
.values_list("title", flat=True)
.all()
)
print(f"pagina {pagina}: {titoli}")
if __name__ == "__main__":
asyncio.run(main())
python ordinamento.py
Output:
--- I tre più letti (3) ---
4: Filtri e lookup in Oxyde | autore 2 | pubblicato | 300 letture
6: Python asincrono per tutti | autore 3 | pubblicato | 210 letture
1: Primi passi con Oxyde | autore 1 | pubblicato | 120 letture
pagina 1: ['Primi passi con Oxyde', 'Le migrazioni spiegate bene', 'Bozza: idee sparse']
pagina 2: ['Filtri e lookup in Oxyde', 'Relazioni tra tabelle', 'Python asincrono per tutti']
pagina 3: ['Bozza: aggregazioni', 'Appunti su SQLite']
The first list shows the three most-read articles, with 300, 210 and 120 views. Then come the three pages of titles: the first and the second contain 3 each, and the third contains 2, because there are 8 articles.
Step 2.6: We compare numbers with lookups
For conditions other than equality, Oxyde, a Python ORM, uses lookups: you write the field name, two underscores and the type of comparison. views__gt=100 means “views greater than 100”, __lte means “less than or equal to”, __between means “between two values, both included”, and __in means “equal to one of the values in the list”. Several lookups in the same filter() are combined with AND, as in the last example.
File confronti.py:
import asyncio
from oxyde import db
from models import Post
from oxyde_config import DATABASES
from stampa import mostra
async def main():
async with db.connect(DATABASES["default"]):
mostra("Più di 100 letture", await Post.objects.filter(views__gt=100).order_by("id").all())
mostra("Al massimo 45 letture", await Post.objects.filter(views__lte=45).order_by("id").all())
mostra(
"Tra 40 e 150 letture",
await Post.objects.filter(views__between=[40, 150]).order_by("id").all(),
)
mostra("Con id 1, 4 o 6", await Post.objects.filter(id__in=[1, 4, 6]).order_by("id").all())
mostra(
"Pubblicati, almeno 50 e meno di 250 letture",
await Post.objects.filter(published=True, views__gte=50, views__lt=250).order_by("id").all(),
)
if __name__ == "__main__":
asyncio.run(main())
python confronti.py
Output:
--- Più di 100 letture (3) ---
1: Primi passi con Oxyde | autore 1 | pubblicato | 120 letture
4: Filtri e lookup in Oxyde | autore 2 | pubblicato | 300 letture
6: Python asincrono per tutti | autore 3 | pubblicato | 210 letture
--- Al massimo 45 letture (4) ---
2: Le migrazioni spiegate bene | autore 1 | pubblicato | 45 letture
3: Bozza: idee sparse | autore 2 | bozza | 0 letture
7: Bozza: aggregazioni | autore 3 | bozza | 0 letture
8: Appunti su SQLite | autore 1 | bozza | 15 letture
--- Tra 40 e 150 letture (3) ---
1: Primi passi con Oxyde | autore 1 | pubblicato | 120 letture
2: Le migrazioni spiegate bene | autore 1 | pubblicato | 45 letture
5: Relazioni tra tabelle | autore 2 | pubblicato | 80 letture
--- Con id 1, 4 o 6 (3) ---
1: Primi passi con Oxyde | autore 1 | pubblicato | 120 letture
4: Filtri e lookup in Oxyde | autore 2 | pubblicato | 300 letture
6: Python asincrono per tutti | autore 3 | pubblicato | 210 letture
--- Pubblicati, almeno 50 e meno di 250 letture (3) ---
1: Primi passi con Oxyde | autore 1 | pubblicato | 120 letture
5: Relazioni tra tabelle | autore 2 | pubblicato | 80 letture
6: Python asincrono per tutti | autore 3 | pubblicato | 210 letture
In the list “Più di 100 letture” only articles with more than 100 views appear, that is, those with 120, 300 and 210. In the list “Tra 40 e 150 letture” only articles with a number of views in that range appear, that is, those with 120, 45 and 80: this way you can see that the comparisons took the right values.
Step 2.7: We search in texts
For text fields there are dedicated lookups: __contains (contains), __startswith (starts with), __endswith (ends with) and __iexact (exactly equal, ignoring upper and lower case). According to the documentation, __contains is case-sensitive and __icontains is not. In the test with SQLite, however, title__contains="oxyde" (lowercase) finds the same two articles as "Oxyde": with this database, __contains made no difference between upper and lower case. The advice is to use __icontains when you want to ignore the difference, and not to rely on __contains to tell it apart.
File testi.py:
import asyncio
from oxyde import db
from models import Author, Post
from oxyde_config import DATABASES
from stampa import mostra
async def main():
async with db.connect(DATABASES["default"]):
mostra('Titolo contiene "Oxyde"', await Post.objects.filter(title__contains="Oxyde").order_by("id").all())
mostra('Titolo contiene "oxyde"', await Post.objects.filter(title__contains="oxyde").order_by("id").all())
mostra('Titolo contiene "oxyde" (icontains)', await Post.objects.filter(title__icontains="oxyde").order_by("id").all())
mostra('Titolo inizia con "Bozza"', await Post.objects.filter(title__startswith="Bozza").order_by("id").all())
print("autori con email @example.com:", await Author.objects.filter(email__endswith="@example.com").count())
carla = await Author.objects.get(name__iexact="carla verdi")
print('iexact "carla verdi":', carla.name)
if __name__ == "__main__":
asyncio.run(main())
python testi.py
Output:
--- Titolo contiene "Oxyde" (2) ---
1: Primi passi con Oxyde | autore 1 | pubblicato | 120 letture
4: Filtri e lookup in Oxyde | autore 2 | pubblicato | 300 letture
--- Titolo contiene "oxyde" (2) ---
1: Primi passi con Oxyde | autore 1 | pubblicato | 120 letture
4: Filtri e lookup in Oxyde | autore 2 | pubblicato | 300 letture
--- Titolo contiene "oxyde" (icontains) (2) ---
1: Primi passi con Oxyde | autore 1 | pubblicato | 120 letture
4: Filtri e lookup in Oxyde | autore 2 | pubblicato | 300 letture
--- Titolo inizia con "Bozza" (2) ---
3: Bozza: idee sparse | autore 2 | bozza | 0 letture
7: Bozza: aggregazioni | autore 3 | bozza | 0 letture
autori con email @example.com: 3
iexact "carla verdi": Carla Verdi
The search with the lowercase term finds the same two articles as the search with the uppercase one, and __icontains gives the same result. The rest of the output shows the list of titles that start with “Bozza”, the count of 3 authors with email @example.com, and the __iexact search, which finds “Carla Verdi” when you write “carla verdi”.
Step 2.8: We filter articles by the author’s data
The foreign key, that is, the column that contains the number of the author of each article, lets us filter articles using the author’s fields: author__name="Carla Verdi". The double underscore here goes across the relationship, and lookups can be added at the end, as in author__email__startswith. Oxyde adds the JOIN by itself, that is, the union between the articles table and the authors table, as you can see in the SQL printed starting from the word FROM.
File per_autore.py:
import asyncio
from oxyde import db
from models import Post
from oxyde_config import DATABASES
from stampa import mostra
async def main():
async with db.connect(DATABASES["default"]):
di_carla = Post.objects.filter(author__name="Carla Verdi").order_by("id")
sql, parametri = di_carla.sql()
print("SQL:", sql[sql.index("FROM"):])
print("parametri:", parametri)
mostra("Articoli di Carla Verdi", await di_carla.all())
mostra(
'Autore con email che inizia per "bruno"',
await Post.objects.filter(author__email__startswith="bruno").order_by("id").all(),
)
if __name__ == "__main__":
asyncio.run(main())
python per_autore.py
Output:
SQL: FROM "posts" LEFT JOIN "authors" AS "author" ON "posts"."author_id" = "author"."id" WHERE "author"."name" = $1 ORDER BY "posts"."id" ASC
parametri: ['Carla Verdi']
--- Articoli di Carla Verdi (2) ---
6: Python asincrono per tutti | autore 3 | pubblicato | 210 letture
7: Bozza: aggregazioni | autore 3 | bozza | 0 letture
--- Autore con email che inizia per "bruno" (3) ---
3: Bozza: idee sparse | autore 2 | bozza | 0 letture
4: Filtri e lookup in Oxyde | autore 2 | pubblicato | 300 letture
5: Relazioni tra tabelle | autore 2 | pubblicato | 80 letture
The first list contains the 2 articles of Carla Verdi, with ids 6 and 7. The second shows the articles of the author whose email starts with “bruno”, that is, Bruno’s 3 articles, and the SQL shows LEFT JOIN between the two tables.
Step 2.9: We load the author together with the article using join()
An article read from the database without join() contains only author_id, the author’s number: in the test the author field is None, which means the author object was not loaded. To also get the author’s name, you use join("author"), which loads the author and the article with a single query. After join(), post.author.name contains the name. The documentation presents this as the way to avoid one extra query for each article.
File carica_autore.py:
import asyncio
from oxyde import db
from models import Post
from oxyde_config import DATABASES
async def main():
async with db.connect(DATABASES["default"]):
senza_join = await Post.objects.order_by("id").first()
print("senza join -> author_id:", senza_join.author_id, "| author:", senza_join.author)
con_join = Post.objects.join("author").order_by("id")
sql, _ = con_join.sql()
print("SQL:", sql[sql.index("FROM"):])
for post in await con_join.all():
print(f"{post.id}: {post.title} | di {post.author.name}")
if __name__ == "__main__":
asyncio.run(main())
python carica_autore.py
Output:
senza join -> author_id: 1 | author: None
SQL: FROM "posts" LEFT JOIN "authors" AS "author" ON "posts"."author_id" = "author"."id" ORDER BY "posts"."id" ASC
1: Primi passi con Oxyde | di Alice Rossi
2: Le migrazioni spiegate bene | di Alice Rossi
3: Bozza: idee sparse | di Bruno Bianchi
4: Filtri e lookup in Oxyde | di Bruno Bianchi
5: Relazioni tra tabelle | di Bruno Bianchi
6: Python asincrono per tutti | di Carla Verdi
7: Bozza: aggregazioni | di Carla Verdi
8: Appunti su SQLite | di Alice Rossi
The first line shows author_id: 1 | author: None: before join() the author is not there. After join(), each article shows the author’s name: for example, the article with id 1 is by Alice Rossi. The SQL shows LEFT JOIN "authors", which means the authors table is read together with the articles table.
Step 2.10: We check what happens when an author is deleted
In the Post model the foreign key has db_on_delete="CASCADE": when you delete an author, the database also deletes their articles. To test this without touching the blog’s data, we create a test author with two articles, then delete it with filter(...).delete(), which returns the number of rows deleted. At the end we count again: the test author’s articles are gone and the totals are back to what they were before. The documentation also lists the other rules: SET NULL (the article stays, without an author) and RESTRICT (the deletion is blocked if the author has articles).
File cancella_autore.py:
import asyncio
from oxyde import db
from models import Author, Post
from oxyde_config import DATABASES
async def main():
async with db.connect(DATABASES["default"]):
prova = await Author.objects.create(name="Autore di prova", email="prova@example.com")
await Post.objects.bulk_create([
Post(title="Prova 1", content="Da cancellare.", author_id=prova.id),
Post(title="Prova 2", content="Da cancellare.", author_id=prova.id),
])
print("articoli dell'autore di prova:", await Post.objects.filter(author_id=prova.id).count())
cancellati = await Author.objects.filter(id=prova.id).delete()
print("autori cancellati:", cancellati)
print("articoli dell'autore di prova dopo:", await Post.objects.filter(author_id=prova.id).count())
print(f"totali: {await Author.objects.count()} autori, {await Post.objects.count()} articoli")
if __name__ == "__main__":
asyncio.run(main())
python cancella_autore.py
Output:
articoli dell'autore di prova: 2
autori cancellati: 1
articoli dell'autore di prova dopo: 0
totali: 3 autori, 8 articoli
The program counts 2 articles for the test author, deletes the author, and then counts zero articles for the same author. The last line goes back to 3 authors and 8 articles, as before the test: this means the blog’s data has not changed.
Step 2.11: We calculate totals, averages, maximums and minimums
Aggregations summarize many rows into a single value, and the database calculates them: count() counts, sum() adds up, avg() calculates the average, and max() and min() find the highest and lowest value of a field. They can be applied after a filter(), as in the last line, which adds up only the views of the published articles.
File totali.py:
import asyncio
from oxyde import db
from models import Post
from oxyde_config import DATABASES
async def main():
async with db.connect(DATABASES["default"]):
print("articoli:", await Post.objects.count())
print("letture totali:", await Post.objects.sum("views"))
print("media letture:", await Post.objects.avg("views"))
print("massimo:", await Post.objects.max("views"))
print("minimo:", await Post.objects.min("views"))
print("letture dei pubblicati:", await Post.objects.filter(published=True).sum("views"))
if __name__ == "__main__":
asyncio.run(main())
python totali.py
Output:
articoli: 8
letture totali: 770
media letture: 96.25
massimo: 300
minimo: 0
letture dei pubblicati: 755
The program prints 8 articles and 770 views in total, with an average of 96.25 views per article. The maximum is 300, the minimum is 0, and the views of the published articles only are 755.
Step 2.12: We group by author
To get a total for each author, you use the combination shown in the documentation: values("author_id") chooses the column to group by, annotate() adds the calculated columns (Count("*") counts the rows in the group, Sum("views") adds up the views), and group_by("author_id") forms the groups. The result is a list of dictionaries, that is, key-value pairs, and not of Post objects. filter() discards rows before grouping (WHERE), while having() discards groups after the calculation (HAVING): in the last example we keep only the authors with more than 200 views in total.
File per_gruppo.py:
import asyncio
from oxyde import Count, Sum, db
from models import Post
from oxyde_config import DATABASES
async def main():
async with db.connect(DATABASES["default"]):
print("--- Per autore ---")
righe = await (
Post.objects.values("author_id")
.annotate(articoli=Count("*"), letture=Sum("views"))
.group_by("author_id")
.order_by("author_id")
.all()
)
for riga in righe:
print(riga)
print("--- Per autore, solo articoli pubblicati (filter = WHERE) ---")
righe = await (
Post.objects.filter(published=True)
.values("author_id")
.annotate(articoli=Count("*"), letture=Sum("views"))
.group_by("author_id")
.order_by("author_id")
.all()
)
for riga in righe:
print(riga)
print("--- Autori con più di 200 letture (having = HAVING) ---")
righe = await (
Post.objects.values("author_id")
.annotate(letture=Sum("views"))
.group_by("author_id")
.having(letture__gt=200)
.order_by("-letture")
.all()
)
for riga in righe:
print(riga)
if __name__ == "__main__":
asyncio.run(main())
python per_gruppo.py
Output:
--- Per autore ---
{'articoli': 3, 'letture': 180, 'author_id': 1}
{'articoli': 3, 'letture': 380, 'author_id': 2}
{'articoli': 2, 'letture': 210, 'author_id': 3}
--- Per autore, solo articoli pubblicati (filter = WHERE) ---
{'articoli': 2, 'letture': 165, 'author_id': 1}
{'articoli': 2, 'letture': 380, 'author_id': 2}
{'articoli': 1, 'letture': 210, 'author_id': 3}
--- Autori con più di 200 letture (having = HAVING) ---
{'letture': 380, 'author_id': 2}
{'letture': 210, 'author_id': 3}
The first list has one row per author, with the number of articles and the sum of the views: the author with id 1 has 3 articles and 180 views. The second list, with filter(), counts only the published articles, while the last one, with having(), shows only the authors with more than 200 views, that is, those with ids 2 and 3.
Step 2.13: Let’s trigger a common error: two filter() calls in a row
We want the articles by Alice, or the ones with at least 100 views. From the data we expect 5 of them: Alice’s three (ids 1, 2 and 8) plus the two by other authors with at least 100 views (ids 4 and 6). A very common mistake is to write two filter() calls in a row, one for each condition. The program ends with a check, assert, which compares the number of articles found with the expected one and stops the program if they do not match. Now we trigger the error on purpose, so you can see up close what happens.
File ricerca_sbagliata.py:
import asyncio
from oxyde import db
from models import Author, Post
from oxyde_config import DATABASES
from stampa import mostra
async def main():
async with db.connect(DATABASES["default"]):
alice = await Author.objects.get(email="alice@example.com")
# Goal: posts by Alice OR with at least 100 views
ricerca = Post.objects.filter(author_id=alice.id).filter(views__gte=100).order_by("id")
sql, parametri = ricerca.sql()
print("SQL:", sql[sql.index("WHERE"):])
print("parametri:", parametri)
trovati = await ricerca.all()
mostra("Trovati", trovati)
assert len(trovati) == 5, f"attesi 5 articoli, trovati {len(trovati)}"
if __name__ == "__main__":
asyncio.run(main())
python ricerca_sbagliata.py > uscita.txt 2> errore.txt
codice=$?
cat uscita.txt
tail -n 1 errore.txt
echo "codice di uscita: $codice"
(exit "$codice")
Output:
SQL: WHERE "author_id" = $1 AND "views" >= $2 ORDER BY "id" ASC
parametri: [1, 100]
--- Trovati (1) ---
1: Primi passi con Oxyde | autore 1 | pubblicato | 120 letture
AssertionError: attesi 5 articoli, trovati 1
codice di uscita: 1
The last line of the message is AssertionError: attesi 5 articoli, trovati 1. AssertionError is the name of the type of error reported by the assert check, while the rest of the line is written in Italian. The codice di uscita: 1 means that the program stopped because of an error.
Oxyde does not report any error, because the query is valid: it simply asks for something else. The printed SQL shows it: WHERE "author_id" = $1 AND "views" >= $2, which means the two conditions are joined by AND, and only one article remains, the one with id 1.
Step 2.14: We fix it with Q expressions and the OR operator
To say “or” you use Q expressions: each one contains a condition, and they are combined with | (OR), & (AND) and ~ (NOT, that is, “not”). Q(author_id=alice.id) | Q(views__gte=100) is exactly the request from before, and the SQL shows OR. A Q expression can also be placed next to normal conditions: in the second example published=True stays in AND with the whole expression, so Alice’s draft is excluded.
File ricerca_corretta.py:
import asyncio
from oxyde import Q, db
from models import Author, Post
from oxyde_config import DATABASES
from stampa import mostra
async def main():
async with db.connect(DATABASES["default"]):
alice = await Author.objects.get(email="alice@example.com")
ricerca = Post.objects.filter(Q(author_id=alice.id) | Q(views__gte=100)).order_by("id")
sql, parametri = ricerca.sql()
print("SQL:", sql[sql.index("WHERE"):])
print("parametri:", parametri)
trovati = await ricerca.all()
mostra("Di Alice oppure con almeno 100 letture", trovati)
assert len(trovati) == 5, f"attesi 5 articoli, trovati {len(trovati)}"
mostra(
"Come sopra, ma solo pubblicati",
await Post.objects.filter(Q(author_id=alice.id) | Q(views__gte=100), published=True)
.order_by("id")
.all(),
)
if __name__ == "__main__":
asyncio.run(main())
python ricerca_corretta.py
Output:
SQL: WHERE "author_id" = $1 OR "views" >= $2 ORDER BY "id" ASC
parametri: [1, 100]
--- Di Alice oppure con almeno 100 letture (5) ---
1: Primi passi con Oxyde | autore 1 | pubblicato | 120 letture
2: Le migrazioni spiegate bene | autore 1 | pubblicato | 45 letture
4: Filtri e lookup in Oxyde | autore 2 | pubblicato | 300 letture
6: Python asincrono per tutti | autore 3 | pubblicato | 210 letture
8: Appunti su SQLite | autore 1 | bozza | 15 letture
--- Come sopra, ma solo pubblicati (4) ---
1: Primi passi con Oxyde | autore 1 | pubblicato | 120 letture
2: Le migrazioni spiegate bene | autore 1 | pubblicato | 45 letture
4: Filtri e lookup in Oxyde | autore 2 | pubblicato | 300 letture
6: Python asincrono per tutti | autore 3 | pubblicato | 210 letture
The first list contains 5 articles, including Alice’s draft “Appunti su SQLite”, and the SQL shows OR. The second, with published=True in AND, contains 4: Alice’s draft is no longer there, and this confirms that the condition in AND excludes drafts.
The most common mistake
The symptom is a search such as “articles by Alice or with at least 100 views” that returns fewer results than expected, with no error message. We met it in step 2.13, where the planned check stopped the program and made us understand that something was wrong.
The cause is that every call to filter() adds a condition that is joined to the previous ones with AND. Two filter() calls one after the other therefore ask for the rows that meet both conditions, not at least one.
The fix is to use Q expressions joined with the | operator for a condition with OR, as in step 2.14. The sql() method shows the generated query, so you can check whether the conditions use AND or OR.
Summary
Post.objectsbuilds a query one piece at a time; the query runs only with a final method such asall(),first()orcount().filter()keeps the rows that meet the conditions,exclude()removes the rows that meet them.order_by()sorts (with-in front of the name for descending order),limit()andoffset()split the results into pages.- Lookups are written with a double underscore:
views__gte=100,title__contains="Oxyde",id__in=[1, 4]. author__name=...filters articles by a field of the author;join("author")loads the author together with the article.- With
db_on_delete="CASCADE", deleting an author also deletes their articles. count(),sum(),avg(),max()andmin()do the calculations in the database;values().annotate().group_by()does them by group.- Several
filter()calls in a row are always joined with AND: for OR you needQexpressions.
Things to keep in mind about Oxyde
- The version used is 0.9.0, so it is a 0.x version: this Python ORM is still young, and later versions may change functions and behavior. For this reason the series pins the version, so the code stays the one that was tested.
- As seen in step 2.7, the behavior of
__containswith upper and lower case does not match the one described in the documentation. To ignore the difference, it is better to use__icontains, without relying on__contains. - The tool does not report an error when the query is valid but asks for the wrong thing, as in step 2.13. An unexpected result passes without messages, and to notice it you need checks such as
assertor thesql()method. - Without
order_by()the database decides the order of the rows, so it is always best to give an explicit sort, as in the steps of this part.
In the next part
In part 3 we will keep the data safe with transactions, that is, groups of operations that either all succeed together or do not succeed at all. We will also learn to handle the tool’s errors, and we turn the mini blog into a small web application with FastAPI.
Glossary
- query: a request for data sent to the database, to read or change rows
- SQL: the standard language used to query and change relational databases
- lookup: a suffix after the double underscore that chooses the type of comparison
- AND: a logical operator that requires all the conditions to be true together
- OR: a logical operator that requires at least one of the conditions to be true
- Q expression: an Oxyde object that represents a condition and can be combined with AND, OR and NOT
- JOIN: an SQL operation that joins the rows of two linked tables
- foreign key: a column that contains the identifier of a row in another table
- CASCADE: a rule that deletes the linked rows when the row they point to is deleted
- aggregation: a calculation that summarizes many rows into a single value, such as a sum or an average
- GROUP BY: an SQL statement that divides rows into groups before the aggregations are calculated
- HAVING: an SQL condition applied to the groups after the aggregations are calculated
A note on the test of Oxyde
The path was tested on Debian 12 with Python 3.11.2 in Docker containers. Other operating systems, such as native Windows and macOS, and databases other than SQLite were not tested.