from django.contrib.auth.models import User import asyncio async def get_first_username(): user = await User.objects.afirst() return user.username if user else 'No user' result = asyncio.run(get_first_username()) print(result)
The afirst() method is the async version of first() in Django ORM. It fetches the first object asynchronously. If a user exists, it returns the username; otherwise, it returns 'No user'.
count after execution?from myapp.models import Product import asyncio async def count_products(): count = await Product.objects.acount() return count count = asyncio.run(count_products())
acount() is the async version of count().The acount() method asynchronously returns the count of records matching the queryset. It returns an integer representing the total number of Product records.
The aall() method asynchronously evaluates the queryset and returns a list of results. You must await it. The afilter() method does not exist; filtering is synchronous but returns an async queryset that you can evaluate with aall().
from django.contrib.auth.models import User async def get_users(): return await User.objects.aall() users = get_users() print(users)
Async functions must be awaited inside an async context or run using asyncio.run(). Calling get_users() directly returns a coroutine, and printing it without awaiting causes a RuntimeError due to no running event loop.
Async ORM methods provide non-blocking database access, which is useful in async views to improve performance. They require an async event loop and do not replace synchronous methods entirely.