0
0
Djangoframework~7 mins

Async ORM operations in Django

Choose your learning style9 modes available
Introduction

Async ORM operations let your Django app handle database tasks without waiting, so it can do other things at the same time. This helps your app stay fast and responsive.

When your app needs to handle many users at once without slowing down.
When you want to fetch or save data without blocking other tasks.
When building real-time features like chat or live updates.
When you want to improve performance by running database queries in the background.
Syntax
Django
await Model.objects.afilter(field=value).afirst()
await Model.objects.acreate(field=value)
await Model.objects.aupdate_or_create(defaults={...}, field=value)
await Model.objects.afilter(field=value).adelete()
Async ORM methods start with 'a' like afirst(), acreate(), aupdate_or_create(), and adelete().
You must use these inside an async function and use await to get the result.
Examples
Fetches the first user asynchronously without blocking.
Django
async def get_user():
    user = await User.objects.afilter().afirst()
    return user
Creates a new post record asynchronously.
Django
async def create_post():
    post = await Post.objects.acreate(title='Hello', content='World')
    return post
Updates or creates a profile asynchronously based on user_id.
Django
async def update_or_create_profile():
    profile, created = await Profile.objects.aupdate_or_create(
        user_id=1,
        defaults={'bio': 'New bio'}
    )
    return profile, created
Sample Program

This example shows how to create, fetch, update, and delete records using Django's async ORM methods inside an async function.

Django
import asyncio
from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=100)

async def async_orm_demo():
    # Create a book asynchronously
    book = await Book.objects.acreate(title='Async Django')
    print(f'Created book: {book.title}')

    # Fetch the first book asynchronously
    first_book = await Book.objects.afilter().afirst()
    print(f'First book title: {first_book.title}')

    # Update or create a book asynchronously
    updated_book, created = await Book.objects.aupdate_or_create(
        title='Async Django',
        defaults={'title': 'Async Django Updated'}
    )
    print(f'Updated book title: {updated_book.title}, Created: {created}')

    # Delete the book asynchronously
    deleted_count, _ = await Book.objects.afilter(title='Async Django Updated').adelete()
    print(f'Deleted books count: {deleted_count}')

asyncio.run(async_orm_demo())
OutputSuccess
Important Notes

Async ORM requires Django 4.1 or newer.

Always run async ORM calls inside async functions and use await.

Not all ORM methods have async versions yet; check Django docs for supported methods.

Summary

Async ORM lets you run database queries without stopping your app.

Use async ORM methods with await inside async functions.

This improves app speed and user experience when handling many tasks.