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

时间:2018-04-27 17:26:02

标签: python database python-3.x peewee

我有这样的模型(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.iddate的列表(要过滤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))

)

我需要使用将返回实际日期而不是记录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

1 个答案:

答案 0 :(得分:1)

您希望模型别名多次引用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”绝对没用。