Skip to main content

Async Django ORM (Django Async Backend)

CI status Latest Version in PyPI Supported Python versions

Monthly downloads

Async Django ORM and PostgreSQL database backend.

๐Ÿ“– Read the documentation


Installation

pip install django-async-backend[binary]

The binary extra installs the C-accelerated psycopg implementation. Without it you get the pure-Python implementation, which is noticeably slower. If you use connection pooling, add the pool extra as well:

pip install django-async-backend[binary,pool]

The package tracks Django's major and minor version โ€” for example 6.0.x matches Django 6.0 โ€” because a large part of the ORM layer is generated from Django's own source.

Quick start

# settings.py
DATABASES = {
    "default": {
        "ENGINE": "django_async_backend.db.backends.postgresql",
        ...
    },
}

INSTALLED_APPS = [
    ...
    "django_async_backend",
]
from django.db import models
from django_async_backend.db import async_connections
from django_async_backend.db.models.base import AsyncModelMixin
from django_async_backend.db.transaction import async_atomic


class Book(AsyncModelMixin, models.Model):
    name = models.CharField(max_length=100)


async def notify(book_id: int) -> None:
    ...


async def main() -> None:
    connection = async_connections["default"]

    async with async_atomic():
        book = await Book.async_objects.acreate(name="Django")

        # async callbacks are supported; runs only if the transaction commits
        await connection.on_commit(lambda: notify(book.pk))

        book.name = "Django Async"
        await book.async_save(update_fields=["name"])

        async with async_atomic():  # savepoint
            await Book.async_objects.filter(name="draft").adelete()

    print(await Book.async_objects.acount())

    async for row in Book.async_objects.order_by("name"):
        print(row.pk, row.name)

Or drop to a raw async cursor:

async with await connection.cursor() as cursor:
    await cursor.execute("SELECT id, name FROM app_book ORDER BY name")

    print(cursor.rowcount)

    async for row in cursor:
        print(row)

[!WARNING] Async does not mean parallel. A task gets one connection per database alias, and every ORM and cursor call in that task takes turns on it โ€” so awaiting several queries in a row does not make them run concurrently.

The connection is owned by the task that first used it, so you cannot fan out onto it either: using it from another task โ€” asyncio.create_task(), asyncio.gather(), asyncio.TaskGroup โ€” raises RuntimeError. Wrapping the fan-out in a single async_atomic() block does not make it safe. To run queries in parallel, give each task its own connection with async_new_connection โ€” sparingly, since each call opens a real connection and a wide fan-out can exhaust the server's limit.

Supported methods

Legend: โœ… supported ยท โŒ not supported ยท โš ๏ธ supported with caveats

QuerySet methods

methods supported comments
Model.objects.aget โœ…
Model.objects.acreate โœ…
Model.objects.acount โœ…
Model.objects.none โœ…
Model.objects.abulk_create โœ…
Model.objects.abulk_update โœ…
Model.objects.aget_or_create โœ…
Model.objects.aupdate_or_create โœ…
Model.objects.aearliest โœ…
Model.objects.alatest โœ…
Model.objects.afirst โœ…
Model.objects.alast โœ…
Model.objects.ain_bulk โœ…
Model.objects.adelete โœ…
Model.objects.aupdate โœ…
Model.objects.aexists โœ…
Model.objects.acontains โœ…
Model.objects.aexplain โœ…
Model.objects.araw โŒ
Model.objects.all โœ…
Model.objects.filter โœ…
Model.objects.exclude โœ…
Model.objects.complex_filter โœ…
Model.objects.union โœ…
Model.objects.intersection โœ…
Model.objects.difference โœ…
Model.objects.select_related โŒ
Model.objects.select_for_update โœ…
Model.objects.prefetch_related โŒ
Model.objects.aaggregate โŒ
Model.objects.annotate โœ…
Model.objects.order_by โœ…
Model.objects.distinct โœ…
Model.objects.extra โœ…
Model.objects.reverse โœ…
Model.objects.defer โš ๏ธ not safe for async, will not be implemented โ€” use values/values_list
Model.objects.only โš ๏ธ not safe for async, will not be implemented โ€” use values/values_list
Model.objects.using โœ…
Model.objects.resolve_expression โœ…
Model.objects.ordered โœ…
Model.objects.values โœ…
Model.objects.values_list โœ…
Model.objects.dates โœ…
Model.objects.datetimes โœ…
Model.objects.alias โœ…
Model.objects.aiterator โŒ

Dunder methods

methods supported comments
__aiter__ โœ…
__iter__ โš ๏ธ raises TypeError โ€” use async for obj in qs
__len__ โš ๏ธ raises TypeError โ€” use await qs.acount()
__contains__ โš ๏ธ falls back to __iter__, so it raises TypeError too
__bool__ โš ๏ธ truth-testing falls back to __len__, so if qs: raises TypeError โ€” use await qs.aexists()
__repr__ โœ…
__and__ โœ…
__or__ โœ…
__xor__ โœ…
__getitem__ โœ…

Model methods

methods supported comments
Model.asave โœ… async_save
Model.adelete โœ… async_delete
Model.arefresh_from_db โŒ

RawQuerySet

Not supported โŒ

Related managers

Not supported โŒ โ€” instance.<related>.all() is the sync ORM. See Pitfalls.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django_async_backend-6.1.3.tar.gz (107.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

django_async_backend-6.1.3-py3-none-any.whl (116.5 kB view details)

Uploaded Python 3

File details

Details for the file django_async_backend-6.1.3.tar.gz.

File metadata

  • Download URL: django_async_backend-6.1.3.tar.gz
  • Upload date:
  • Size: 107.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.1.1 CPython/3.12.14 Linux/6.17.0-1022-azure

File hashes

Hashes for django_async_backend-6.1.3.tar.gz
Algorithm Hash digest
SHA256 ef973170695f7b736ea36055e8582baee445473ef9722aa77df46291228162c6
MD5 67f99126756e6dca4eee674285e08331
BLAKE2b-256 3aab43abb5dd90610c08f9c39174bc2de6c56f670bf45e0d66817a30af98634a

See more details on using hashes here.

File details

Details for the file django_async_backend-6.1.3-py3-none-any.whl.

File metadata

  • Download URL: django_async_backend-6.1.3-py3-none-any.whl
  • Upload date:
  • Size: 116.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.1.1 CPython/3.12.14 Linux/6.17.0-1022-azure

File hashes

Hashes for django_async_backend-6.1.3-py3-none-any.whl
Algorithm Hash digest
SHA256 7118a2f77203a81b8d00e39bcc0bdf3f2682ba1ffcb2a65c09142be7fa82edf2
MD5 2754481f70386da04c261dca5eea0ecb
BLAKE2b-256 a872598fea6dd8a2520dde5c25a576c3b3006ee95a2d181d2620907eae58c696

See more details on using hashes here.

Release history Release notifications | RSS feed

This release

6.1.3 This release

2 files

6.1.2

2 files

6.1.1

2 files

6.1.0

2 files

6.0.9

2 files

6.0.8

2 files

6.0.7

2 files

6.0.6

2 files

6.0.5

2 files

0.0.4

2 files

0.0.3

2 files

0.0.2

2 files

0.0.1

2 files

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page