【问题标题】:Multiple joins in peeweepeewee 中的多个连接
【发布时间】:2014-02-18 09:28:28
【问题描述】:

我被难住了。因此,我在 peewee 中定义了三个模型:

class Patient(BaseModel):
    patientIdx = IntegerField()
    gender = CharField()
    firstName = CharField()
    middleInit = CharField()
    lastName = CharField()
    provider = ForeignKeyField(User)
    MRN = CharField()
    class Meta:
        database = database

class Metrics(BaseModel):
    metricId = CharField( )
    metricDescription = CharField()
    ptListDescription = CharField()
    class Meta:
        database = database

class PatientMetric(BaseModel):
    metric = ForeignKeyField(Metrics)
    patient = ForeignKeyField(Patient)
    class Meta:
        database = database

我正在尝试使用 peewee 来表达这个 mySQL 查询:

select m.metricId, p.id from
patient as p
join patientmetric pm on p.id = pm.patient_id
join metrics m on pm.metric_id = m.id
where provider_id = 91

基本上,只需给我一份患者列表以及给定提供商的指标 ID。很简单,但我不知道如何让 peewee 做到这一点。我试过链接连接,但 peewee 无法解析外键。 我尝试过以几种不同的方式使用 .join 以及 .from_ 方法,例如:

Metrics.select()
        .from_(
            PatientMetric.select().join(Patient).where(Patient.provider == provider),
            Metrics)
        .where(Metrics.id == PatientMetric.metric)

在这种情况下,mySQL 抱怨需要创建派生表的别名。我想我找错了树,有一种简单的方法可以在 peewee 中构建这个查询,但我很难过。谁能告诉我“正确”的方式?

【问题讨论】:

    标签: peewee


    【解决方案1】:
    query = (Patient
             .select(Metrics.metricId, Patient.id)
             .join(PatientMetric)
             .join(Metrics)
             .where(Patient.provider == 91)
             .tuples() # <-- since you just need the metric id and patient id
    )
    

    【讨论】:

      猜你喜欢
      • 2014-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-03
      • 2015-02-18
      • 2018-05-28
      • 2018-10-26
      • 1970-01-01
      相关资源
      最近更新 更多