Quick start
An existing Django project gets async views in a FastAPI application.
Install
pip install "adorm[django]" fastapi uvicornDjango models
The schema is defined and migrated by Django, as usual:
# mysite/library/models.py
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
born = models.DateField(null=True, blank=True)
class Book(models.Model):
class Genre(models.TextChoices):
FICTION = "fiction", "Fiction"
POETRY = "poetry", "Poetry"
SCIENCE = "science", "Science"
title = models.CharField(max_length=200)
genre = models.CharField(max_length=20, choices=Genre.choices, default=Genre.FICTION)
author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name="books")
published = models.DateField()
copies = models.PositiveIntegerField(default=1)python manage.py makemigrations library
python manage.py migrateGenerate the adorm models
adorm generate --settings mysite.settings --output mysite/adorm_models librarywrote mysite/adorm_models/__init__.py
wrote mysite/adorm_models/library.py
2 written, 0 removed, 0 unchanged.The generated module is checked into the repository and regenerated after every model change; adorm generate --check fails when it is stale (Generating models). mysite/adorm_models/library.py:
class Author(Model):
_meta = ModelMeta("library.Author", schema_hash="5bbba558fb8a2821")
id: int | None = None
name: str = Field(max_length=100)
born: datetime.date | None = None
books = ReverseForeignKey("library.Book", column="author_id")
class Book(Model):
_meta = ModelMeta("library.Book", schema_hash="c6b06aa3a5dc4a7a")
id: int | None = None
title: str = Field(max_length=200)
genre: Literal["fiction", "poetry", "science"] = "fiction"
author_id: int
published: datetime.date
copies: int = Field(default=1, ge=0)
author = ForeignKey("library.Author")The models are pydantic models: Book.model_json_schema() and FastAPI response models work on them. Django's field options become pydantic types and constraints: choices a Literal, max_length and validators Field constraints, so Book(genre="drama", ...) raises a validation error before anything reaches the database. author and books are relations: await book.author loads the author, author.books is a query.
Set up
Add adorm's Django app. It configures adorm from DATABASES when Django is set up:
# mysite/settings.py
INSTALLED_APPS = [
...,
"mysite.library",
"adorm.contrib.django",
]The FastAPI application sets Django up before it imports the models:
# mysite/main.py
import django
django.setup()
from fastapi import FastAPI, HTTPException
from mysite.library_service import author_overview, lend
app = FastAPI()
@app.get("/authors/{name}")
async def get_author(name: str) -> dict:
return await author_overview(name)
@app.post("/books/{book_id}/loans")
async def post_loan(book_id: int) -> dict:
try:
book = await lend(book_id)
except LookupError as exc:
raise HTTPException(409, str(exc)) from exc
return {"title": book.title, "copies_left": book.copies}Write queries
# mysite/library_service.py
import asyncio
import datetime
import adorm
from adorm import Count, Q, Sum
from mysite.adorm_models.library import Author, Book
async def author_overview(name: str) -> dict:
author = await Author.objects.get(name__iexact=name)
books = author.books.order_by("-published") # a query; nothing runs yet
total, shelf = await asyncio.gather( # two queries at once
books.count(),
Book.objects.aggregate(titles=Count("id"), on_loan=Count("id", filter=Q(copies=0)), copies=Sum("copies")),
)
newest = await books.select_related("author").first()
recent = books.filter(published__gte=datetime.date(2000, 1, 1)).values_list("title", flat=True)
return {
"author": author.name,
"titles": total,
"since_2000": [title async for title in recent],
"newest": f"{newest.title} by {(await newest.author).name}" if newest else None,
"shelf": shelf,
}
@adorm.atomic() # each call is one transaction
async def lend(book_id: int) -> Book:
book = await Book.objects.select_for_update().get(pk=book_id)
if book.copies == 0:
raise LookupError(f"no copy of {book.title!r} left")
book.copies -= 1
await book.save(update_fields=["copies"])
return book- Building a query (
filter(),order_by(),select_related()) does no I/O.awaitruns it:get(),first(),count(),aggregate(),update();async foriterates the rows. @adorm.atomic()runs each call oflend()in a transaction: it commits when the function returns and rolls back when it raises.async with adorm.atomic():does the same for a block.select_for_update()locks the row until the transaction ends: two concurrentlend()calls for the last copy run one after the other, and the second raisesLookupError.
Run it:
DJANGO_SETTINGS_MODULE=mysite.settings uvicorn mysite.main:appNext
- Making queries: lookups,
Q,F, relations, set operations. - Transactions: savepoints,
on_commit(), timeouts. - Sessions and the pool: slots, acquisition timeouts, deadlock detection.
- Testing: adorm under Django's
TestCase. - Drivers: the native PostgreSQL driver, which runs without threads.