Skip to Main Content
Essential SQLAlchemy
book

Essential SQLAlchemy

by Rick Copeland
June 2008
Intermediate to advanced content levelIntermediate to advanced
230 pages
6h 29m
English
O'Reilly Media, Inc.
Content preview from Essential SQLAlchemy

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning PostgreSQL

Learning PostgreSQL

Salahaldin Juba, Achim Vannahme, Andrey Volkov
Practical PostgreSQL

Practical PostgreSQL

Joshua D. Drake, John C. Worsley
PostgreSQL

PostgreSQL

Korry Douglas, Susan Douglas
Learning PostgreSQL 11 - Third Edition

Learning PostgreSQL 11 - Third Edition

Christopher Travers, Andrey Volkov

Publisher Resources

ISBN: 9780596516147Supplemental ContentErrata Page