SQL 更新似乎沒有被制定,也沒有拋出任何錯誤。下面是我的代碼的簡化版本。對于背景關系,模型中的“選擇”欄位是默認值為 False 的布爾欄位,用戶可以(理想情況下)通過發送帶有“選擇”事件和“是”訊息的 JSON 包來更改它。
消費者.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
我試圖在這里只包含相關代碼,但如果需要更多,請告訴我。提前致謝!
uj5u.com熱心網友回復:
我通過在行await前添加解決了這個問題sync_to_async(room.update)(choice=True)。似乎沒有await它會在完成 SQL 更新之前移動到下一行代碼,導致更新無法通過。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/451672.html
