[Answered ]-Django multi table inheritance represented with SQLAlchemy

2👍

There are basically two ways to present the data in CommonParent and ChildA in a single model: in Django, ChildA knows it has a parent in the table for CommonParent. SQLAlchemy uses a different approach, where CommonParent knows it has a child in the table for ChildA. On a database level you use Django’s method, so that’s what you want to mimic in your SQLAlchemy code.

More specifically, in Django, whenever you query for a CommonParent, you only get the data associated with the CommonParent class, and when you query for a ChildA, you get the data for both ChildA and CommonParent through a join clause.

The CommonParent class works good as it is in SQLAlchemy:

class CommonParent(Base):
  __tablename__ = '<tablename>'

  id = Column(Integer, primary_key=True)
  field = Column(String)

For the ChildA class you want to define a custom mapper that always performs a join statement:

metadata = MetaData()

parent_table = CommonParent.__table__
child_table = Table('<tablename>', metadata,
              Column('id', Integer, primary_key=True),
              Column('commonparent_ptr', Integer, ForeignKey('<tablename>.id'))
             )

childa = join(parent_table, child_table)

class ChildA(Base):
  __table__ = childa

  id = column_property(parent_table.c.id, child_table.c.user_id)
  child_id = child_table.c.id

(Documentation)

👤knbk

Leave a comment