python / intermediate
Snippet
Asynchronous QuerySet Iteration in Async Django Views
Django supports native asynchronous views using 'async def'. When querying models inside async views, using 'async for' allows non-blocking database streaming over QuerySets.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
from django.http import JsonResponsefrom .models import AuditLogasync def stream_audit_logs(request):log_titles = []async for entry in AuditLog.objects.filter(is_active=True).order_by('-created_at'):log_titles.append(entry.action_title)if len(log_titles) >= 50:breakreturn JsonResponse({'recent_actions': log_titles})
django
Breakdown
1
async def stream_audit_logs(request):
Declare an asynchronous view handler compatible with ASGI application servers.
2
async for entry in AuditLog.objects.filter(is_active=True).order_by('-created_at'):
Iterate asynchronously over QuerySet records without blocking the async event loop.
3
log_titles.append(entry.action_title)
Collect fields from model instances into an in-memory accumulator list.
4
return JsonResponse({'recent_actions': log_titles})
Return an asynchronous HTTP JSON response containing the fetched audit records.