2014-02-16 2 views
3

나는 혼란 스럽다. peewee 사용하여 나는이 MySQL의 쿼리를 표현하기 위해 노력하고있어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 

을 : 나는 thusly 히 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 

, 단지 나에게 환자의 목록과 ID의 제공 해당 제공자에 대한 측정 항목 아주 간단하지만, 나는 peewee가 이것을 어떻게하는지 주위에 내 머리를 얻을 수 없습니다. 조인 체인 연결 시도했지만 peewee 외래 키를 해결할 수 없습니다. 나는 예를 들어, 여러 가지 방법으로 .join 사용하여 시도하고 .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 
)