3

I am integrating django channels for async capabilites. I am trying to fetch multiple objects of a user model using await on the function.

consumers.py

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.

Arsh Doda
  • 294
  • 4
  • 14

1 Answers1

5

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.

Chris
  • 300
  • 1
  • 6