What is Django's asynchronous views (ASGI)?
Why Interviewers Ask This
Advanced questions like this reveal whether a candidate has internalized Django deeply enough to make architectural decisions. Strong answers demonstrate both breadth and depth of experience.
Answer
Django 3.1+ supports async views via ASGI, allowing non-blocking I/O operations without blocking the server thread. Async view: import asyncio import aiohttp from django.http import JsonResponse async def aggregate_data(request): async with aiohttp.ClientSession() as session: tasks = [ session.get("https://api1.example.com/data"), session.get("https://api2.example.com/data"), session.get("https://api3.example.com/stats"), ] responses = await asyncio.gather(*tasks) results = [await r.json() for r in responses] return JsonResponse({"data": results}). Async ORM (Django 4.1+): async def user_list(request): users = [u async for u in User.objects.filter(is_active=True)[:100]] # or: users = await User.objects.filter(is_active=True).values_list("id", "username") return JsonResponse({"users": list(users)}). Async ORM methods: await obj.asave(), await obj.adelete(), await Model.objects.aget(pk=1), await Model.objects.acreate(...), await qs.acount(), await qs.aexists(), await qs.afirst(), async for item in qs:. sync_to_async: wrap synchronous code for use in async context: from asgiref.sync import sync_to_async get_user = sync_to_async(lambda pk: User.objects.get(pk=pk)). async_to_sync: call async code from sync context: from asgiref.sync import async_to_sync result = async_to_sync(async_function)(). Running with ASGI: uvicorn myproject.asgi:application --workers 4 or Daphne. Async views only help for I/O-bound work. CPU-bound: use Celery workers.
Pro Tip
Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex Django answers easy to follow.
More Django Questions
View all →- Advanced What is Django's select_for_update and database locking?
- Advanced What is Django's database optimization with query analysis?
- Advanced What is Django's transaction management in depth?
- Advanced What is Django's deployment best practices?
- Advanced What is Django's caching strategies and cache invalidation?