Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django 3.1 - async views - working with querysets

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 ?

like image 658
Pydev UA Avatar asked Mar 21 '26 14:03

Pydev UA


1 Answers

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())
like image 71
Saksham Mittal Avatar answered Mar 23 '26 03:03

Saksham Mittal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!