The SQL update does not seem to be being enacted upon, and no errors are being thrown either. Below is a simplified version of my code. For context, the "choice" field in the model is a Boolean Field with a default of False, and a user may (ideally) change this by sending a JSON package with the "CHOICE" event and "Yes" message.
consumers.py
import json
from channels.generic.websocket import AsyncJsonWebsocketConsumer
from asgiref.sync import sync_to_async
from .models import Room
class Consumer(AsyncJsonWebsocketConsumer):
async def connect(self):
self.room_code = self.scope['url_route']['kwargs']['room_code']
#Websockets connection code
async def disconnect(self):
#Websockets disconnect code
async def receive(self, text_data):
response = json.loads(text_data)
event = response.get("event", None)
message = response.get("message", None)
if event == "CHOICE":
room_set = await sync_to_async(Room.objects.filter)(room_code=self.room_code)
room = await sync_to_async(room_set.first)()
if (not room.choice) and message["choice"] == 'Yes':
sync_to_async(room_set.update)(choice=True) #line seems to not be working
elif room.choice and message["choice"] == 'No':
sync_to_async(room_set.update)(choice=False)
#code to send message to group over Websockets
#code regarding other events
async def send_message(self, res):
#Websockets send message code
I've tried to only include the relevant code here, but if more is needed please let me know. Thanks in advance!
CodePudding user response:
I fixed this issue by adding await
before the sync_to_async(room.update)(choice=True)
lines. It seems without an await
it will move onto the next line of code before completing the SQL update, causing the update to not go through.