Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sqlalchemy (and alembic) Concrete table inheritance without polymorphic union

I'm new to SQLAlchmey, and I'm trying to achieve the following objects/db tables structure (by using alembic as well):

class BaseConfig(Base):
 pk = Column(Integer, primary_key=True)
 name = Column(Unicode(150), nullable=False, unique=True)
 ...
 # Lots of other general columns, such as description, display_name, creation time etc.

And I want all other configuration classes to inherit the predefined columns from it:

class A(BaseConfig):
  __tablename__ = "A"
  column1 = Column...
  column2 = Column...

class B(BaseConfig):
  __tablename__ = "B"
  column1 = Column...
  column2 = Column...

The BaseConfig table is not a real table, only a class that holds common columns. Other than that - nothing is related between A and B, and no need for a shared pk etc. It seems that using "polymorphic_union" is not relevant here as well.

By trying to run alembic autogenerate I get the error that BaseConfig doesn't have a table mapped class - which is true, and i really don't see a reason to add the "polymorphic union" option to BaseConfig, since this class is generic. Any suggestions? (In Django with south this works out of the box, but here it seems that this behavior is not supported easily).

Thanks, Li

like image 492
Lin Avatar asked Oct 23 '25 05:10

Lin


1 Answers

Either use MixIns (read Mixing in Columns part of the documentation), where your BaseConfig does not subclass Base and actual tables subclass both Base and BaseConfig:

class BaseConfig(object):
    # ...

class MyModel(BaseConfig, Base):
    # ...

OR simply use __abstract__:

class BaseConfig(Base):
    __abstract__ = True
like image 145
van Avatar answered Oct 24 '25 19:10

van