'How i can use "database_sync_to_async" function for fetching multiple object
I am implementing a consumer, and y want get all productos for example:
class MyConsumer(AsyncConsumer):
async def get_all_producs():
products = await database_sync_to_async(Products.objects.all)()
When i try fetch all products from the above code causes the error "You cannot call this from an async context - use a thread or sync_to_async."
I know that query are lazy, but, how i can get all products?
Solution 1:[1]
As far as I understand, that is not possible. Turn your query data into a dictionary and return that.
@database_sync_to_async
def get_all_producs():
products = Products.objects.all()
dic = {}
for p in products:
dic[p.pk] = p.data
return dic
Note: You cannot send back the object directly as objects are not JSON serializable.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user9911049 |
