Reputation: 263
I'm trying to create a very simple system where an user, in order to use a consumer, needs to input a key in the WS url, like : ws://127.0.0.1:8000/main?key=KEY
. Once the consumer is called, Django Channels needs to perform a very simple DB query to check if the key exists:
class TestConsumer(AsyncJsonWebsocketConsumer):
async def websocket_connect(self, event):
...
key_query = await database_sync_to_async(keys.objects.get(key=key))
...
But the problem with this code is that it will give the following error:
You cannot call this from an async context - use a thread or sync_to_async.
Is there any way to accomplish this? Any advice is appreciated!
Upvotes: 2
Views: 1653
Reputation: 35032
database_sync_to_async
must be called on the method, not on the result of the method:
key_query = await database_sync_to_async(keys.objects.get)(key=key)
Upvotes: 1