我在使用 sync_to_async 時遇到問題。You cannot call this from an async context - use a thread or sync_to_async.即使我使用sync_to_async 來轉換異步函式,我在列印陳述句中也遇到了錯誤。如果我這樣做print(type(masters)),我會得到一個 QuerySet 作為型別。有什么我想念的嗎?我在檔案中找不到這個具體案例。
這是我的代碼:
import discord
from discord.ext import commands
from asgiref.sync import sync_to_async
class Bot(commands.Bot):
# ...
async def on_message(self, msg):
masters = await sync_to_async(self.subject.masters)()
print(masters)
這是我試圖從中獲取結果的 masters() 函式:
from django.db import models
class Subject(models.Model):
# ...
def masters(self):
from .subjectmaster import SubjectMaster
return SubjectMaster.objects.filter(subject=self)
uj5u.com熱心網友回復:
sync_to_async您的 QuerySet 在列印之前不會執行,并且您在函式之外列印。您需要在您的方法中評估 QuerySet
class Subject(models.Model):
def masters(self):
from .subjectmaster import SubjectMaster
# Force evaluation by converting to a list
return list(SubjectMaster.objects.filter(subject=self))
一個選項,如果您不希望從該masters方法回傳一個串列,是sync_to_async在該list函式上運行并將您的查詢集傳遞給它
masters = await sync_to_async(list)(self.subject.masters())
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/469320.html
上一篇:UI僅在第二次單擊時更新
