Friday, 31 December 2021

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()


from Django Model Property in Async Function Called from Sync View

No comments:

Post a Comment