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

3 投票
1 回答
3343 浏览
提问于 2025-04-20 17:01

我有一个基础类的混合类:

class MyColumns(object):
    id = Column(Integer)
    foo = Column(Integer)
    bar = Column(Integer)

class MyMainTable(MyColumns, Base):
    __tablename__ = 'main_table'
    pk_id = PrimaryKeyConstraint("id")

我想在中把id声明为主键(PK)。但是我不能在MyColumns中声明它为主键,因为我还需要在另一个表中使用MyColumns,而在那个表里,id并不是主键(这样做是为了审计的目的)。当我运行上面的代码时,我得到了

sqlalchemy.exc.ArgumentError: Mapper Mapper|MyMainTable|main_table could not assemble any primary key columns for mapped table 'main_table'

有没有什么办法可以这样添加主键声明呢?

1 个回答

4

我找到了解决办法,具体内容可以在这里查看: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"),
    )

撰写回答