【问题标题】:How to get values from `ForeignKeyField` using peewee in join query?如何在连接查询中使用 peewee 从“ForeignKeyField”中获取值?
【发布时间】:2018-04-27 17:26:02
【问题描述】:

我有这样的模型 (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.ids 和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))

)

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

【问题讨论】:

    标签: python database python-3.x peewee


    【解决方案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”绝对没用。

    【讨论】:

      猜你喜欢
      • 2014-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-22
      • 2016-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多