我正在尝试使用过滤器和偏移/限制查询模型。然后对于每个井,我希望获得最新的场景,如果有的话最好批准。然后对于每个场景得到它的下降参数
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,那么我会根据整个井列表而不是每个井获得两个最新的场景!如何调整查询以获得所需的结果?