Self-referential foreign keys

When creating a heirarchical structure it is necessary to create a self-referential foreign key which links a child object to its parent. Because the model class is not defined at the time you instantiate the self-referential foreign key, use the special string 'self' to indicate a self-referential foreign key:

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

As you can see, the foreign key points upward to the parent object and the back-reference is named children.

Attention

Self-referential foreign-keys should always be null=True.

When querying against a model that contains a self-referential foreign key you may sometimes need to perform a self-join. In those cases you can use Model.alias() to create a table reference. Here is how you might query the category and parent model using a self-join:

  1. Parent = Category.alias()
  2. GrandParent = Category.alias()
  3. query = (Category
  4. .select(Category, Parent)
  5. .join(Parent, on=(Category.parent == Parent.id))
  6. .join(GrandParent, on=(Parent.parent == GrandParent.id))
  7. .where(GrandParent.name == 'some category')
  8. .order_by(Category.name))