Мне необходимо получить данные из БД внутри асинхронной функции. Если я получаю только один объект выполняя, например:
users = await sync_to_async(Creators.objects.first)()
все работает как надо. Но если ответ содержит несколько объектов, я получаю ошибку.
Мой код:
@sync_to_async
def get_creators():
return Creators.objects.all()
async def CreateBotAll():
users = await get_creators()
for user in users:
print(user)
Traceback (most recent call last):
File "/home/django/django_venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/django/django_venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/django/django_venv/src/reseller/views.py", line 29, in test
asyncio.run(TgAssistant.CreateBotAll())
File "/usr/lib/python3.8/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/usr/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
return future.result()
File "/home/django/django_venv/src/reseller/TgAssistant.py", line 84, in CreateBotAll
for user in users:
File "/home/django/django_venv/lib/python3.8/site-packages/django/db/models/query.py", line 280, in __iter__
self._fetch_all()
File "/home/django/django_venv/lib/python3.8/site-packages/django/db/models/query.py", line 1324, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "/home/django/django_venv/lib/python3.8/site-packages/django/db/models/query.py", line 51, in __iter__
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File "/home/django/django_venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1173, in execute_sql
cursor = self.connection.cursor()
File "/home/django/django_venv/lib/python3.8/site-packages/django/utils/asyncio.py", line 31, in inner
raise SynchronousOnlyOperation(message)
django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.
Django==3.2.12
asgiref==3.5.0