我有一个基类混合:
class MyColumns(object):
id = Column(Integer)
foo = Column(Integer)
bar = Column(Integer)
class MyMainTable(MyColumns, Base):
__tablename__ = 'main_table'
pk_id = PrimaryKeyConstraint("id")
我希望能够将 id
声明为 MyMainTable 上的主键。我不能在 MyColumns
中将其声明为 PK,因为我需要在另一个表中使用 MyColumns
,其中 id 不是 PK(用于审计目的)。当我运行上面的代码时,我得到了
sqlalchemy.exc.ArgumentError: Mapper Mapper|MyMainTable|main_table could not assemble any primary key columns for mapped table 'main_table'
有什么办法可以这样添加PK声明吗?
最佳答案
我找到了此处记录的解决方案:http://docs.sqlalchemy.org/en/rel_0_9/core/constraints.html#setting-up-constraints-when-using-the-declarative-orm-extension
您需要将约束添加到__table_args__
:
class MyColumns(object):
id = Column(Integer)
foo = Column(Integer)
bar = Column(Integer)
class MyMainTable(MyColumns, Base):
__tablename__ = 'main_table'
__table_args__ = (
PrimaryKeyConstraint("id", name="pk_id"),
)
关于python - SQLAlchemy:可以以声明方式将列声明为主键吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25749803/