我很难过。我在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无法解析外键。 我尝试过以几种不同的方式使用.join,以及.from_方法,例如:
Metrics.select()
.from_(
PatientMetric.select().join(Patient).where(Patient.provider == provider),
Metrics)
.where(Metrics.id == PatientMetric.metric)
在这种情况下,mySQL抱怨需要创建派生表的别名。我想我正在咆哮错误的树,并且有一种简单的方法可以在peewee中构建这个查询,但我很难过。任何人都可以向我展示'正确'的方式吗?
答案 0 :(得分:3)
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
)