Home > Back-end >  Using Django 4.1 async orm in FastAPi
Using Django 4.1 async orm in FastAPi

Time:08-10

In verson 4.1 some async stuff was added to orm part of Django. I want to use Django orm in fastAPi, I created a small setting file for using Django orm like this:

import os
import sys
import django
from django.conf import settings

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
INSTALLED_APPS = [
    'django.contrib.contenttypes',
    'django.contrib.auth',
    'orm',
]
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'db',
        'USER': 'user',
        'PASSWORD': 'pass',
        'HOST': '127.0.0.1',
        'PORT': '5432',
    }
}
settings.configure(
    DATABASES = DATABASES,
    INSTALLED_APPS = INSTALLED_APPS,
)
django.setup()

if __name__ == "__main__":
    from django.core.management import execute_from_command_line

    execute_from_command_line(sys.argv)

I want to run a query is main file like this in FastApi:

from django.core.paginator import Paginator
@app.get("/test-orm")
async def test_django_orm():
    results = await User.objects.filter(username="user0")
    paginator = Paginator(results, 2)
    paginated = json.loads(serializers.serialize('json', paginator.page(1)))
    return {"data": paginated}

This code simple doesn't work! here is error:

TypeError: object QuerySet can't be used in 'await' expression

If I remove async and await it works perfectly, but I write to use async friendly code!

CodePudding user response:

As you may read in documentation or other related threads in SO, you should use function sync_to_async from asgiref. Take a look here:

Modern best approach to using Django ORM with async?

and here in documentation: https://docs.djangoproject.com/en/4.0/topics/async/#asgiref.sync.sync_to_async

https://docs.djangoproject.com/en/4.0/topics/async/#async-views

CodePudding user response:

you can use django-async-orm module for the async DB calls.

and you can read the docs here: https://github.com/rednaks/django-async-orm

Only issue with the module is, it is still in development phase, means it is not for production.

  • Related