如何在连接查询中使用 peewee 从 `ForeignKeyField` 获取值?

How to get values from `ForeignKeyField` using peewee in join query?

我有这样的模型 (peewee 2.10):

class LegalAct(Model):
    start_date = DateField()
    expiration_date = DateField()

class SomeModel(Model):
    name = CharField()
    legal_act = ForeignKeyField(LegalAct)

class OtherModel(Model):
    name = Charfield()
    some_model = ForeignKeyField(SomeModel) 
    starting_legal_act = ForeignKeyField(LegalAct)
    closing_legal_act = ForeignKeyField(LegalAct)

class ExtraModel(Model):
    value = IntegerField()
    other_model = ForeignKeyField(OtherModel) 
    starting_legal_act = ForeignKeyField(LegalAct)
    closing_legal_act = ForeignKeyField(LegalAct)

给定 SomeModle.id 列表和一个 date(用于过滤 LegalAct)我想获得以下数据:

SomeModel.name
OtherModel.name
OtherModel.starting_legal_act.start_date
ExtraModel.starting_legal_act.start_date
ExtraModel.value

问题是我不知道如何遍历 OtherModel.starting_legal_act.start_dateExtraModel.starting_legal_act.start_date - 我只能得到 id 对应的模型并获取结果查询中的数据。

我现在的代码是这样的:

other_model_legal_act = get_other_legal_act(date)  # a query
extra_model_legal_act = get_extra_legal_act(date)  # a query

data = OtherModel.select(
    SomeModel.name
    OtherModel.name
    OtherModel.starting_legal_act.alias('date_1')  # I get `id`, but want date
    ExtraModel.starting_legal_act.alias('date_2')  # I get `id`, but want date
    ExtraModel.value
).join(SomeModel).switch(OtherModel).join(ExtraModel).where(
    (OtherModel.legal_act == other_model_legal_act) &
    (ExtraModel.legal_act == extra_model_legal_act) &
    (SomeModel.id.in_(id_list))

)

我需要用 return 实际日期而不是记录 ID 的代码替换这些行:

OtherModel.starting_legal_act.alias('date_1')  # I get `id`, but want date
ExtraModel.starting_legal_act.alias('date_2')  # I get `id`, but want date

您希望模型别名多次引用 LegalAct:

LegalAct1 = LegalAct.alias()
LegalAct2 = LegalAct.alias()

data = OtherModel.select(
    SomeModel.name
    OtherModel.name
    LegalAct1.start_date.alias('date_1'),
    LegalAct2.start_date.alias('date_2'),
    OtherModel.starting_legal_act.alias('date_1')  # I get `id`, but want date
    ExtraModel.starting_legal_act.alias('date_2')  # I get `id`, but want date
    ExtraModel.value
)
.join(LegalAct1, on=(OtherModel.starting_legal_act == LegalAct.id))
.switch(OtherModel)
# 

等等

将来...请尝试使您的模型更易于推理。 "SomeModel" 和 "OtherModel" 完全没用。