Several connections in peewee

I'm at a dead end. Thus, I have three Models defined in 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

I am trying to express this mySQL query with 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 an identifier of their indicators for this provider. Pretty simple, but I can't figure out how to get peewee to do this. I tried to bind connections, but peewee cannot resolve foreign keys. I tried using .join in several ways and with the .from_ method, for example:

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

In this case, mySQL complained about the need to create an alias for the view. I think I'm barking the wrong tree, and there is an easy way to build this request in peewee, but I'm at a dead end. Can someone show me the “correct” way?

+3
source share
1 answer
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
)
+3
source

All Articles