Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Async Model Save()

I'm converting my normal views to async views due to request queries blocking all my threads. So far I've solved most of my problems except one. How to async save a model?

async def dashboardAddChart(request, rowId):
    row = (await sync_to_async(list)(DashboardRow.objects.filter(pk=rowId).select_related('dashboard__site', 'dashboard__theme')))[0]

    chart = DashboardChart(dashboard=row.dashboard, dashboardRow=row)
    
    if row.dashboard.theme is not None:
        dashboardThemes.applyThemeToChart(chart)

    chart.save()

    chartData = await getChartData(chart.pk)

I've tried numerous things with chart.save() including:

await sync_to_async(chart.save)

t = asyncio.ensure_future(sync_to_async(chart.save))
await asyncio.gather(t)

But I'm not getting it right.

Any help will be appreciated!

like image 960
ceds Avatar asked Oct 24 '25 19:10

ceds


2 Answers

await sync_to_async(chart.save)

should be

await sync_to_async(chart.save)()

The sync_to_async function wraps chart.save and returns an asynchronous version of it, which then still has to be called to execute.

like image 80
eriks5 Avatar answered Oct 27 '25 10:10

eriks5


models in Django ≥ 4.2 have the asave method

like image 42
am70 Avatar answered Oct 27 '25 08:10

am70