3 ms·
I don't fully understand the sync_to_async() operation here. So the underlying database is not async, then is Django just tossing the sync DB call onto a thread
by aynyc 4y ago
I don't fully understand the sync_to_async() operation here. So the underlying database is not async, then is Django just tossing the sync DB call onto a thread or something?
- Ralfp 4y agoexactly, it fires database call in a separare thread with coroutine awaiting this threads result.
- megaman821 4y agoYes, it is just being put on a thread. A future Django release will use async database drivers. Django is very incrementally adding support for async. I don't believe they have started work on async templates yet, which will be one of the last major areas before the framework is fully async.
- collinmanderson 4y agoYes, they're working from the top of the stack down, so first it was views+middleware, now it's the top layer of the database stack, and in future releases they'll work on pushing native async lower and lower in the stack. Basically every function call that does db-queries needs an "a"-prefixed version. aget(), acreate(), aget_or_create(), acount(), aexists(), aiterator(), __aiter__, etc. And in future versions they'll work on the lower level, undocumented api, like _afetch_all(), aprefetch_related_objects(), compiler.aexecute_sql(), etc. Eventually you'll probably need to switch database drivers to something that actually supports async.
- hansonkd13 4y agoWhy do they need Async templates? When a template renders it should be pure data and fully on the CPU. It seems Async templates would encourage a bad behavior of doing n+1 queries inside the HTML.
- megaman821 4y agoMy immediate thought would be custom template tags. Like `{% popular_articles %}` would have to connect to the DB and load the articles. I am sure there are other reasons too.
- simonw 4y agoDjango makes a lot of use of lazy evaluation. You'll often construct a QuerySet object in a Django view like this: entries = Entry.objects.filter( category="python" ).order_by("-created")[:10] Then pass that to a template which does this: {% for entry in entries %}... Django doesn't actually execute the SQL query until the template starts looping through it. Async template rendering becomes necessary if you want the templates to be able to execute async SQL queries in this way. Jinja has this feature already with the enable_async=True setting - I wrote a tiny bit about that in https://til.simonwillison.net/sqlite/related-content https://til.simonwillison.net/sqlite/related-content