Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django await on a function with @database_sync_to_async decorator for fetching multiple object throws error

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.

like image 530
Arsh Doda Avatar asked Oct 19 '25 18:10

Arsh Doda


1 Answers

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.

like image 123
Chris Avatar answered Oct 22 '25 08:10

Chris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!