看似简单的情况:Django模型有外键:
class Invite(models.Model):
inviter = models.ForeignKey(User, on_delete=models.CASCADE)
...
在异步上下文中,我会:
# get invite with sync_to_async decorator, then
print(invite.inviter)
获取async最喜欢的错误:
第一个月
print(sync_to_async(invite.inviter)) # -> throws the same error
当然,我可以:
@sync_to_async
def get_inviter(self, invite):
return invite.inviter
但是,如果我必须为每个queryset属性调用都这样做,这就太老土了。
有没有理智的方法来处理这件事?
也许,有一种方法可以同时为所有这样的调用做到这一点?
2条答案
按热度按时间w8ntj3qf1#
是,使用
select_related
解析额外字段:其他string non-foreign 属性(如string和int属性)应该已经存在于模型中。
不起作用,(尽管他们觉得应该起作用)
其他研究示例
执行标准
aget
,然后执行外键检查,会产生SynchronousOnlyOperation
错误。我有一个字符串
key
和一个指向标准用户模型的外键user
。下面是一个几乎不起作用的替代方案的示例:
50few1ms2#
这是因为它等价于:
正确用法是:
有没有理智的方法来处理这件事?
也许,有一种方法可以同时为所有这样的调用做到这一点?
(免责声明:未在生产中测试。)
使用nest_asyncio,您可以执行以下操作:
或者更进一步: