Django support for asynchronous database engines

1.4k Views Asked by At

I can't find information about django support for asynchronous database engines. For example for postgresql django supports only psycopg2 library, that is completely synchronous and nothing more is supported, for sqlite django supports only sqlite3 library that is synchronous as well. So I'm not well orientiered in django and of course I can be mistaken, but what's the sense of django asgi if it doesn't support asynchronous database engines(I mean, then all the asynchronous code becomes synchronous) ?

And the second question, is there any way to use asynchronous engines in django ?

2

There are 2 best solutions below

1
On

This is from the Django Docs

*Are you looking for what kind of database async support? *

# DJANGO_SETTINGS_MODULE=settings.py python -m asyncio
>>> import asyncio
>>> from asgiref.sync import sync_to_async
>>> from django.db import connection
>>> # In an async context so you cannot use the database directly:
>>> connection.cursor()

django.core.exceptions.SynchronousOnlyOperation: You cannot call this from
an async context - use a thread or sync_to_async.
>>> # Nor can you pass resolved connection attributes across threads:
>>> await sync_to_async(connection.cursor)()
...
django.db.utils.DatabaseError: DatabaseWrapper objects created in a thread
can only be used in that same thread. The object with alias 'default' was
created in thread id 4371465600 and this is thread id 6131478528.

https://docs.djangoproject.com/en/4.0/topics/async/

0
On

As far as I know there is no support for async in Django ORM. So you should consider using different framework or integrate different ORM like sqlalchemy

Here is what they say in the doc: "We’re still working on async support for the ORM and other parts of Django. You can expect to see this in future releases. For now, you can use the sync_to_async() adapter to interact with the sync parts of Django. There is also a whole range of async-native Python libraries that you can integrate with."

For your second question: Configuring Django to use SQLAlchemy

But I would strongly recommend to consider switching framework if you don't have a lot django bonded written code. To something like FastAPI, or aiohttp