简体   繁体   中英

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

I have a base class 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. 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). 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?

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

You need to add the constraints to __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"),
    )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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