预取在 Tortoise-ORM 中没有按预期工作

问题描述

我正在尝试使用过滤器和偏移/限制来查询模型。 然后对于每个 Well 我想获得最新的场景,如果有的话最好获得批准。 然后对于每个场景获取其下降参数

results = await models.Well.filter(field_name=field_name)\
    .order_by("well_name").offset(offset).limit(limit)\
    .prefetch_related(\
        Prefetch("scenarios",queryset=models.Scenarios.all()\
        .order_by("-is_approved","-created_at").limit(1).prefetch_related(\
                Prefetch("decline_parameters",queryset=models.Decline_Parameters.filter(label="best").all(),\ 
                to_attr="best_decline_parameters")\
         ),to_attr="latest_scenario")\
    ).all()

class Well(Model):
    id = fields.IntField(pk=True)
    well_name = fields.CharField(max_length=255,unique=True,null=False)
    field_name = fields.CharField(max_length=255,null=False)
    created_on = fields.DatetimeField(null=False,auto_Now=True)
    scenarios: fields.ReverseRelation["Scenarios"]

class Scenarios(Model):
    id = fields.IntField(pk=True)
    description = fields.CharField(max_length=1000,null=False)
    created_at = fields.DatetimeField(null=False,auto_Now=True)
    #bunch of fields
    is_approved = fields.BooleanField(default=False)
    well : fields.ForeignKeyRelation[Well] = fields.ForeignKeyField("models.Well",related_name="scenarios")
    decline_parameters: fields.ReverseRelation["Decline_Parameters"]


class Decline_Parameters(Model):
    id = fields.IntField(pk=True)
    #bunch of fields
    label = fields.CharField(max_length=255,null=False)
    scenario: fields.ForeignKeyRelation[Scenarios] = fields.ForeignKeyField("models.Scenarios",related_name="decline_parameters")

我得到的结果是所需的孔列表。然而,只有一口井有场景。如果我将场景的限制增加到2,那么我会根据整个井列表而不是每个井来获取两个最新的场景! 如何调整查询以获得所需的结果?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)