3

I'm stumped. I've got three Models defined in peewee thusly:

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

I'm trying to express this mySQL query using 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

Basically, just give me a list of patients and the ID of their metrics for a given provider. Pretty simple, but I can't get my head around how to make peewee do this. I've tried chaining the joins, but peewee can't resolve the foreign keys. I've tried using .join in several different ways, and the .from_ method, for instance:

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

In this case, mySQL complained that an alias for the derived table needed to be created. I think I'm barking up the wrong tree and there is a simple way to build this query in peewee, but I'm stumped. Can anyone show me the 'right' way?

4

1 回答 1

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
)
于 2014-02-18T01:28:28.977 回答