Inheritance =========== .. _joined-table-inheritance-example: Joined Table ------------ SQLAlchemy includes a feature where a model class hierarchy is implemented by giving each class it's own table. For example, an :samp:`Employee` might have an :samp:`id`, :samp:`name` and :samp:`type`. Then a :samp:`Manager` model might be defined that derives from :samp:`Employee` and adds the :samp:`manager_data` column. .. seealso:: :ref:`joined-table-inheritance` OpenAlchemy documentation for joined table inheritance. `SQLAlchemy joined table inheritance documentation `_ Documentation for SQLAlchemy joined table inheritance. The following example defines joined tabled inheritance where :samp:`Employee` is the parent and :samp:`Manager` and :samp:`Engineer` derive from it: .. literalinclude:: ../../../examples/inheritance/joined-example-spec.yml :language: yaml :linenos: The following file uses OpenAlchemy to generate the SQLAlchemy models: .. literalinclude:: ../../../examples/inheritance/joined_models.py :language: python :linenos: The SQLAlchemy models generated by OpenAlchemy are equivalent to the following traditional models file: .. literalinclude:: ../../../examples/inheritance/joined_models_traditional.py :language: python :linenos: OpenAlchemy will generate the following typed models: .. literalinclude:: ../../../examples/inheritance/joined_models_auto.py :language: python :linenos: .. _single-table-inheritance-example: Single Table ------------ Single table inheritance is very similar to :ref:`joined-table-inheritance` with the difference that all classes are linked to the same table and there is no foreign key relationship between the models. .. seealso:: :ref:`single-table-inheritance` OpenAlchemy documentation for single table inheritance. `SQLAlchemy single table inheritance documentation `_ Documentation for SQLAlchemy single table inheritance. The following example defines single tabled inheritance where :samp:`Employee` is the parent and :samp:`Manager` and :samp:`Engineer` derive from it: .. literalinclude:: ../../../examples/inheritance/single-example-spec.yml :language: yaml :linenos: The following file uses OpenAlchemy to generate the SQLAlchemy models: .. literalinclude:: ../../../examples/inheritance/single_models.py :language: python :linenos: The SQLAlchemy models generated by OpenAlchemy are equivalent to the following traditional models file: .. literalinclude:: ../../../examples/inheritance/single_models_traditional.py :language: python :linenos: OpenAlchemy will generate the following typed models: .. literalinclude:: ../../../examples/inheritance/single_models_auto.py :language: python :linenos: .. seealso:: :ref:`getting-started`