2014-02-16 61 views
3

我很難過。使用peewee在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 

我想表達這個MySQL查詢:我有在peewee正是如此定義的三種型號

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 

基本上,只要給我的病人的列表和標識他們對給定提供者的指標。很簡單,但我無法理解如何讓peewee做到這一點。我嘗試鏈接連接,但peewee無法解析外鍵。 我在幾種不同的方式使用。加入試過,和.from_方法,例如:

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

在這種情況下,MySQL抱怨說,要創建的需要派生表的別名。我想我在咆哮錯誤的樹,並有一個簡單的方法來構建這個查詢peewee,但我很難過。任何人都可以向我展示'正確'的方式嗎?

回答

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 
)