Accessing ForeignKeyField attributes in query using Peewee in Python

28 Views Asked by At

My database looks something like this:

class ModelA(BaseModel): 
  id = AutoField() 
  b = ForeignKeyField(ModelB) 
  c = ForeignKeyField(ModelC) 
  extra = CharField() 

class ModelB(BaseModel): 
  id = AutoField() 
  a = ForeignKeyField(ModelA) 
  c = ForeignKeyField(ModelC) 
  extra = CharField() 

class ModelC(BaseModel): 
  id = AutoField() 
  b = ForeignKeyField(ModelB) 
  a = ForeignKeyField(ModelA) 
  extra = CharField() 

and I want to perform a query to get rows from ModelA joined with ModelB where ModelA.c.id are certain values.

Something like:

sample = ModelA.select(ModelA, ModelB) 
    .join(ModelB, on=ModelA.b) 
    .where(ModelA.c.id = specific_c_id) 

This doesn't work. But I think I am misunderstanding something about how .where() works after the .join(). Or maybe I need to use aliases (which I don't fully understand). What is the right way to perform a query like this?

1

There are 1 best solutions below

0
On

If you want to query for a specific value in the ModelA.c, then:

sample = (ModelA.select(ModelA, ModelB) 
    .join(ModelB, on=ModelA.b) 
    .where(ModelA.c = specific_c_id))