简体   繁体   English

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

[英]SQLAlchemy: Possible to declare a column as primary key declaratively?

I have a base class mixin: 我有一个基类mixin:

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

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

I want to be able to declare id as the PK on MyMainTable. 我希望能够将id声明为MyMainTable上的PK。 I can't declare it as PK within MyColumns , because I need to use MyColumns in another table, where id is NOT the PK (done for auditing purposes). 我无法在MyColumns其声明为PK,因为我需要在另一个表中使用MyColumns ,其中id不是PK(出于审计目的而做)。 When I run the above code, I get 当我运行上面的代码时,我得到

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

Is there any way to add the PK declaration this way? 有什么办法可以这样添加PK声明吗?

I found the solution as documented here: http://docs.sqlalchemy.org/en/rel_0_9/core/constraints.html#setting-up-constraints-when-using-the-declarative-orm-extension 我找到了此处记录的解决方案: http : //docs.sqlalchemy.org/en/rel_0_9/core/constraints.html#setting-up-constraints-when-using-the-declarative-orm-extension

You need to add the constraints to __table_args__ : 您需要将约束添加到__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"),
    )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM