I am integrating django channels for async capabilites. I am trying to fetch multiple objects of a user model using await on the function.
class TeamConsumer(AsyncConsumer):
async def websocket_connect(self, event):
await self.send({
"type":"websocket.accept"
})
async def websocket_receive(self, event):
o_user = await self.users()
print(o_user)
@database_sync_to_async
def users(self):
return UserModel.objects.all()
Trying to fetch users from the above code causes the error "You cannot call this from an async context - use a thread or sync_to_async."
However if i fetch a single object using "UserModel.objects.all().first()", everything works fine.
I think it's because querysets are lazy. Calling UserModel.objects.all() doesn't actually execute the query. The query is getting executed when you print it. Try converting it to a list inside the users() method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With