Since 3.1 (currently beta) Django have support for async views
async def myview(request):
users = User.objects.all()
This example will not work - since ORM is not yet async ready
so what's the current workaround ?
you cannot just use sync_to_async with queryset - as they it is not evaluated:
from asgiref.sync import sync_to_async
async def myview(request):
users = await sync_to_async(User.objects.all)()
so the only way is evaluate queryset inside sync_to_async:
async def myview(request):
users = await sync_to_async(lambda: list(User.objects.all()))()
which looks very ugly
any thoughts on how to make it nicer ?
There is a common GOTCHA: Django querysets are lazy evaluated (database query happens only when you start iterating):
so instead - use evaluation (with list):
from asgiref.sync import sync_to_async
async def myview(request):
users = await sync_to_async(list)(User.objects.all())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With