Skip to main content
 首页 » 编程设计

python之Sqlalchemy(和 alembic)没有多态联合的具体表继承

2025年05月04日16虾米姐

我是 SQLAlchmey 的新手,我正在尝试实现以下对象/数据库表结构(也通过使用 alembic):

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. 

我希望所有其他配置类都从它继承预定义的列:

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

BaseConfig 表不是真正的表,只是一个包含公共(public)列的类。 除此之外 - A 和 B 之间没有任何关系,也不需要共享 pk 等。似乎使用“polymorphic_union”在这里也不相关。

通过尝试运行 alembic autogenerate,我得到了 BaseConfig 没有表映射类的错误 - 这是真的,而且我真的没有看到将“多态联合”选项添加到 BaseConfig 的原因,因为这类是通用的。 有什么建议么? (在带有 south 的 Django 中,这是开箱即用的,但在这里似乎不容易支持这种行为)。

谢谢, 李

请您参考如下方法:

要么使用 MixIns(阅读文档的 Mixing in Columns 部分),其中您的 BaseConfig not 子类 Base 和实际表子类Base 和 BaseConfig:

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

或只需使用 __abstract__ :

class BaseConfig(Base): 
    __abstract__ = True