同步到异步Django ORM查询集外键属性

ajsxfq5m  于 2022-12-24  发布在  Go
关注(0)|答案(2)|浏览(102)

看似简单的情况: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属性调用都这样做,这就太老土了。
有没有理智的方法来处理这件事?
也许,有一种方法可以同时为所有这样的调用做到这一点?

w8ntj3qf

w8ntj3qf1#

是,使用select_related解析额外字段:

# Good: pick the foreign_key fields using select_related
user = await Invite.objects.select_related('user').aget(key=key).user

其他string non-foreign 属性(如string和int属性)应该已经存在于模型中。
不起作用,(尽管他们觉得应该起作用)

# Error django.core.exceptions.SynchronousOnlyOperation ... use sync_to_async
user = await Model.objects.aget(key=key).user
# Error (The field is actually missing from the `_state` fields cache.
user = await sync_to_async(Invite.objects.get)(key=key).user

其他研究示例

执行标准aget,然后执行外键检查,会产生SynchronousOnlyOperation错误。
我有一个字符串key和一个指向标准用户模型的外键user

class Invite(models.Model):
    user = fields.user_fk()
    key = fields.str_uuid()

下面是一个几乎不起作用的替代方案的示例:

Invite = get_model('invites.Invite')
User = get_user_model()

def _get_invite(key):
    return Invite.objects.get(key=key)

async def invite_get(self, key):
    # (a) works, the related field is populated on response.
    user = await Invite.objects.select_related('user').aget(key=key).user
   

async def intermediate_examples(self, key):
    # works, but is clunky.
    user_id = await Invite.objects.aget(key=key).user_id
    # The `user_id` (any `_id` key) exists for a FK
    user = await User.objects.aget(id=user_id)

async def failure_examples(self, key):
    # (b) does not work. 
    user = await sync_to_async(Invite.objects.get)(key=key).user
    invite = await sync_to_async(Invite.objects.get)(key=key)

    # (c) these are not valid, although the error may say so.
    user = await invite.user
    user = await sync_to_async(invite.user)

    # same as the example (b)
    get_invite = sync_to_async(_get_invite, thread_sensitive=True)
    invite = get_invite(key)
    user = invite.user # Error 
    
    # (d) Does not populate the additional model
    user = await Invite.objects.aget(key=key).user # Error
50few1ms

50few1ms2#

print(sync_to_async(invite.inviter))  # -> throws the same error

这是因为它等价于:

i = invite.inviter  # -> throws the error here
af = sync_to_async(i)
print(af)

正确用法是:

f = lambda: invite.inviter
af = sync_to_async(f)
i = await af()
print(i)

# As a one-liner
print(await sync_to_async(lambda: invite.inviter)())

有没有理智的方法来处理这件事?
也许,有一种方法可以同时为所有这样的调用做到这一点?
(免责声明:未在生产中测试。)
使用nest_asyncio,您可以执行以下操作:

def do(f):
    import nest_asyncio
    nest_asyncio.apply()
    return asyncio.run(sync_to_async(f)())

print(do(lambda: invite.inviter))

或者更进一步:

class SynchronousOnlyAttributeHandler:
    def __getattribute__(self, item):
        from django.core.exceptions import SynchronousOnlyOperation
        try:
            return super().__getattribute__(item)
        except SynchronousOnlyOperation:
            from asgiref.sync import sync_to_async
            import asyncio
            import nest_asyncio
            nest_asyncio.apply()
            return asyncio.run(sync_to_async(lambda: self.__getattribute__(item))())
class Invite(models.Model, AsyncUnsafeAttributeHandler):
    inviter = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    ...
# Do this even in async context
print(invite.inviter)

相关问题