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 model alias to represent the second instance of the table in a query. Consider the following 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 is Electronics. 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 to specify the join condition using the on keyword argument. In this case we are joining the category with its parent category.

Using subqueries

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

  1. Parent = Category.alias()
  2. join_query = Parent.select().where(Parent.name == 'Electronics')
  3. # Subqueries used as JOINs need to have an alias.
  4. join_query = join_query.alias('jq')
  5. query = (Category
  6. .select()
  7. .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 lookup which will generate the appropriate SQL expression:

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