1
0
mirror of https://github.com/django/django.git synced 2025-06-12 15:09:12 +00:00

[3.1.x] Refs #31224 -- Made sync_to_async() examples use thread sensitive with ORM calls.

Backport of 8d59075184f4cd2852b374359850ff7aeb412ec1 from master
This commit is contained in:
Mariusz Felisiak 2020-09-03 11:33:23 +02:00 committed by Carlton Gibson
parent 17d5b16dbf
commit f36c441f80

View File

@ -73,17 +73,18 @@ you will need to wrap it in a :func:`sync_to_async` call. For example::
from asgiref.sync import sync_to_async from asgiref.sync import sync_to_async
results = sync_to_async(Blog.objects.get)(pk=123) results = await sync_to_async(Blog.objects.get, thread_sensitive=True)(pk=123)
You may find it easier to move any ORM code into its own function and call that You may find it easier to move any ORM code into its own function and call that
entire function using :func:`sync_to_async`. For example:: entire function using :func:`sync_to_async`. For example::
from asgiref.sync import sync_to_async from asgiref.sync import sync_to_async
@sync_to_async def _get_blog(pk):
def get_blog(pk):
return Blog.objects.select_related('author').get(pk=pk) return Blog.objects.select_related('author').get(pk=pk)
get_blog = sync_to_async(_get_blog, thread_sensitive=True)
If you accidentally try to call a part of Django that is still synchronous-only If you accidentally try to call a part of Django that is still synchronous-only
from an async view, you will trigger Django's from an async view, you will trigger Django's
:ref:`asynchronous safety protection <async-safety>` to protect your data from :ref:`asynchronous safety protection <async-safety>` to protect your data from