Django 在带有@database_sync_to_async 装饰器的函数上等待获取多个对象抛出错误

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

我正在为异步功能集成 Django 通道。我正在尝试在函数上使用 await 来获取用户模型的多个对象。

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()

尝试从上述代码中获取用户会导致错误 "You cannot call this from an async context - use a thread or sync_to_async."

但是,如果我使用 "UserModel.objects.all().first()" 获取单个对象,一切正常。

我认为这是因为查询集是惰性的。调用 UserModel.objects.all() 实际上并不执行查询。当您打印查询时,查询将被执行。尝试将其转换为 users() 方法中的列表。