Self-joins

Peewee supports constructing queries containing a self-join.

Using model aliases

To join on the same model (table) twice, it is necessary to create a modelalias to represent the second instance of the table in a query. Consider thefollowing model:

  1. class Category(Model):
  2. name = CharField()
  3. parent = ForeignKeyField('self', backref='children')

What if we wanted to query all categories whose parent category isElectronics. One way would be to perform a self-join:

  1. Parent = Category.alias()
  2. query = (Category
  3. .select()
  4. .join(Parent, on=(Category.parent == Parent.id))
  5. .where(Parent.name == 'Electronics'))

When performing a join that uses a ModelAlias, it is necessary tospecify the join condition using the on keyword argument. In this case weare joining the category with its parent category.

Using subqueries

Another less common approach involves the use of subqueries. Here is anotherway we might construct a query to get all the categories whose parent categoryis Electronics using a subquery:

  1. Parent = Category.alias()
  2. join_query = Parent.select().where(Parent.name == 'Electronics')
  3.  
  4. # Subqueries used as JOINs need to have an alias.
  5. join_query = join_query.alias('jq')
  6.  
  7. query = (Category
  8. .select()
  9. .join(join_query, on=(Category.parent == join_query.c.id)))

This will generate the following SQL query:

  1. SELECT t1."id", t1."name", t1."parent_id"
  2. FROM "category" AS t1
  3. INNER JOIN (
  4. SELECT t2."id"
  5. FROM "category" AS t2
  6. WHERE (t2."name" = ?)) AS jq ON (t1."parent_id" = "jq"."id")

To access the id value from the subquery, we use the .c magic lookupwhich will generate the appropriate SQL expression:

  1. Category.parent == join_query.c.id
  2. # Becomes: (t1."parent_id" = "jq"."id")