簡體   English   中英

如何在聯接查詢中使用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))

)

我需要將這些行替換為將返回實際日期而不是記錄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”絕對沒有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM