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?

1 Answer

I found the solution as documented here:

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"),
    )
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest