Chapter 8. Inheritance Mapping
In this chapter, you will learn the different methods of mapping object-oriented inheritance to relational database tables. You will learn how to use different methods of inheritance mapping with SQLAlchemy, as well as how to use inheritance in the presence of mapped relations between classes.
Overview of Inheritance Mapping
No object-relational mapper would be complete without some method of mapping object-oriented inheritance hierarchies to SQL tables, and so SQLAlchemy provides rich support for modeling inheritance. Inheritance is typically modeled in SQL in one of three ways: single table inheritance, concrete table inheritance, or joined table inheritance.
For the purposes of illustrating SQLAlchemy’s support for the various types of inheritance modeling, we will use a simple inheritance hierarchy that models products, including clothing products and accessories. This hierarchy is illustrated in Figure 8-1 and is implemented by the following Python code:
class Product(object): def __init__(self, sku, msrp): self.sku = sku self.msrp = msrp def __repr__(self): return '<%s %s>' % ( self.__class__.__name__, self.sku) class Clothing(Product): def __init__(self, sku, msrp, clothing_info): Product.__init__(self, sku, msrp) self.clothing_info = clothing_info class Accessory(Product): def __init__(self, sku, msrp, accessory_info): Product.__init__(self, sku, msrp) self.accessory_info = accessory_info
Figure 8-1. Sample inheritance hierarchy
Single Table Inheritance ...
Get Essential SQLAlchemy now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.