Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Model Property in Async Function Called from Sync View

I need to convert some of my Django views to work with async functions that query data sources. I'm experiencing big performance issues as those queries are executed one by one in series. However, the task is much harder than anticipated.

I've indicated below where the problems start. I'm experiencing other problems as well, however, this is by far the one that I don't have a clue on what to do. I get the following error where indicated in the code below:

django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async

model2 is a ForeignKey property pointing to another Model.

Wrapping model1.model2 inside sync_to_async() does not work.

Any idea how to make this work ?

async def queryFunctionAsync(param1, param2, loop):
   model1 = await sync_to_async(Model1.objects.get)(pk=param1)
   model2 = model1.model2 # This is where the error is generated

def exampleView(request):
   loop = asyncio.new_event_loop()
   asyncio.set_event_loop(loop)
   data = async_to_sync(queryFunctionAsync)(param1, param2, loop)
   loop.close()
like image 405
ceds Avatar asked Jul 29 '26 12:07

ceds


1 Answers

This worked for me:

model2 = await sync_to_async(lambda: model1.model2)()

After that model1 also contains the reference.

like image 139
Rolando Retana Avatar answered Jul 31 '26 02:07

Rolando Retana



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!