SQLAlchemy:可以声明性地将列声明为主键吗?

时间:2014-09-09 16:36:37

标签: python sqlalchemy

我有一个基类mixin:

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上的PK。我不能在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声明?

1 个答案:

答案 0 :(得分:3)

我找到了解决方案,如下所示: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"),
    )