← Back to Django, page 2

django-0035 · Hard senior

How do async views and the async ORM work in Django 5.x, and what are their limits?

An async view is an async def function (or a class with async handlers) that Django runs on the event loop under ASGI. The ORM offers async methods such as aget(), acreate(), acount(), aexists() and async for over QuerySets, but under the hood most database calls still run in a thread through sync_to_async because database drivers used by Django are synchronous. Async views pay off for I/O such as calling external APIs concurrently, not for CPU work or plain ORM pages.

Full answer

Django has supported async views since 3.1 and an async ORM interface since 4.1. In Django 5.x:

  • A view written as async def runs on the event loop when served by an ASGI server (Uvicorn, Daphne, Hypercorn). Under WSGI, Django runs it in a one-off event loop per request, which gives no concurrency benefit.
  • Class-based views can define async def get(); all handlers on the class must be either sync or async.
  • QuerySet methods have a-prefixed versions: aget, afirst, acreate, aupdate, adelete, acount, aexists, aaggregate, ain_bulk, and async for obj in qs. Model instances have asave, adelete, arefresh_from_db.
  • Django 5.0 added aget_object_or_404, async auth functions such as aauthenticate() and alogin(), and async signal dispatch (asend()).

The limit: Django's database backends are still synchronous. Async ORM calls are wrapped with sync_to_async and run in a thread pool, one at a time per connection. So an async view that only runs ORM queries is not faster than a sync view; it can even be slightly slower because of thread hops.

Where async helps: a view that waits on several slow outside services. Calling three APIs with httpx.AsyncClient and asyncio.gather takes about as long as the slowest one, instead of the sum.

Rules:

  • Never call blocking code (requests, time.sleep, sync ORM) directly in an async view. Django raises SynchronousOnlyOperation for sync ORM calls in an async context. Wrap legacy code with sync_to_async.
  • Transactions: transaction.atomic() does not support async yet; put transactional work in a sync function and call it with sync_to_async.
  • Sync middleware in the stack makes Django switch threads for each request, eating the gain. Check that middleware is async-capable.
  • Accessing lazy relations (book.author) in async code triggers a sync query and raises; use select_related or await sync_to_async(...).
python
import sys
import tempfile
import types

import django
from django.conf import settings

# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    ALLOWED_HOSTS=["testserver"],  # the host name used by Django's test client
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": tempfile.mkdtemp() + "/school.sqlite3"}},
)
django.setup()

import asyncio
import time

from asgiref.sync import sync_to_async
from django.core.exceptions import SynchronousOnlyOperation
from django.db import models, connection
from django.http import JsonResponse
from django.test import AsyncRequestFactory


class Student(models.Model):
    name = models.CharField(max_length=40)
    marks = models.IntegerField()
    class Meta:
        app_label = "school"


with connection.schema_editor() as editor:
    editor.create_model(Student)


async def fetch_service(name, delay):
    await asyncio.sleep(delay)       # stands in for an httpx.AsyncClient call
    return name


async def dashboard(request):
    count = await Student.objects.filter(marks__gte=40).acount()
    names = [s.name async for s in Student.objects.order_by("name")]
    start = time.perf_counter()
    services = await asyncio.gather(fetch_service("fees", 0.3), fetch_service("library", 0.3),
                                    fetch_service("hostel", 0.3))
    took = time.perf_counter() - start
    return JsonResponse({"passed": count, "names": names, "services": services,
                         "concurrent": took < 0.6})


async def main():
    await Student.objects.acreate(name="Sneha", marks=72)
    await Student.objects.acreate(name="Vikram", marks=35)
    response = await dashboard(AsyncRequestFactory().get("/dashboard/"))
    print(response.content.decode())
    try:
        Student.objects.count()      # sync ORM call inside async code
    except SynchronousOnlyOperation:
        print("sync ORM call blocked inside the event loop")
    print(await sync_to_async(Student.objects.count)())


asyncio.run(main())

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. The three services are simulated with asyncio.sleep; real code would use httpx.AsyncClient. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): {"passed": 1, "names": ["Sneha", "Vikram"], "services": ["fees", "library", "hostel"], "concurrent": true} sync ORM call blocked inside the event loop 2

Key points

  • async def views run on the event loop under ASGI
  • Async ORM methods use the a- prefix and async for
  • Database calls still run in threads; no speedup for ORM-only views
  • Gain comes from concurrent external I/O
  • Sync ORM in async code raises SynchronousOnlyOperation; atomic() is sync only

Common mistakes

  • Expecting async views full of ORM queries to be faster than sync views
  • Calling requests or time.sleep inside async def and blocking the event loop
  • Running async views under WSGI and expecting concurrency
  • Using transaction.atomic() directly in async code
  • Leaving sync-only middleware in an ASGI stack

Follow-ups

  • Why is the async ORM still thread-based in Django 5.x?
  • How would you call a legacy sync function from an async view safely?
  • When would you choose FastAPI instead of async Django?

Tips

  • Say plainly where async helps and where it does not
  • Name SynchronousOnlyOperation and sync_to_async
  • Mention ASGI as a requirement for real concurrency