django / channels

Developer-friendly asynchrony for Django
https://channels.readthedocs.io
BSD 3-Clause "New" or "Revised" License
6.02k stars 793 forks source link

How to execute several database access in async consumers #2041

Closed wenyuan closed 11 months ago

wenyuan commented 11 months ago

Environment:

Description:

When i want to access database in async consumers, i can do like this:

from channels.db import database_sync_to_async

async def connect(self):
    self.username = await self.get_name()

@database_sync_to_async
def get_name(self):
    return User.objects.all()[0].name

but how can i execute several database query operations in one wrapped method?

the following code will throw exception: You cannot call this from an async context - use a thread or sync_to_async.

from channels.db import database_sync_to_async

async def connect(self):
    user, orders, messages = await self.get_user_data(1)

@database_sync_to_async
def get_user_data(self):
    user = User.objects.get(id=user_id)
    orders =Order.objects.filter(user=user)
    messages = Message.objects.filter(user=user)
    return user, orders, messages

Thank you very much for your answer and if you can give me some clues~

wenyuan commented 11 months ago

It was an unexpected small error that I have fixed, thanks to the project