未制定 Django 异步模型更新

Django async model update not being enacted

SQL 更新似乎没有被执行,也没有抛出任何错误。下面是我的代码的简化版本。对于上下文,模型中的“选择”字段是一个默认值为 False 的布尔字段,用户可以(理想情况下)通过发送带有“选择”事件和“是”消息的 JSON 包来更改它.

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

我已尝试在此处仅包含相关代码,但如果需要更多代码,请告诉我。提前致谢!

我通过在 sync_to_async(room.update)(choice=True) 行之前添加 await 解决了这个问题。似乎没有 await 它会在完成 SQL 更新之前移动到下一行代码,导致更新无法通过。