Search code examples
djangopython-asynciodjango-channels

Modern best approach to using Django ORM with async?


The world of async Django is changing rapidly, and it's hard to tell what is current and what is dated.

So, what is the current best approach to using the Django ORM (or, possibly, another ORM) for the best/smoothest async capability? What do people use successfully today?

Lots of references out there, including:

One problem I have is that no matter what I try, I run into the "django.db.utils.OperationalError: database "test_djangoasyncproj" is being accessed by other users" issue.


Solution

  • If you are using Django >= 4.2

    Asynchronous support

    Django has support for writing asynchronous (“async”) views, along with an entirely async-enabled request stack if you are running under ASGI. Async views will still work under WSGI, but with performance penalties, and without the ability to have efficient long-running requests.

    async for author in Author.objects.filter(name__startswith="A"):
        book = await author.books.afirst()
    
    
    async def make_book(*args, **kwargs):
        book = Book(...)
        await book.asave(using="secondary")
    
    
    async def make_book_with_tags(tags, *args, **kwargs):
        book = await Book.objects.acreate(...)
        await book.tags.aset(tags)
    

    source: https://docs.djangoproject.com/en/4.2/topics/async/