This example shows how to create, fetch, update, and delete records using Django's async ORM methods inside an async function.
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())