Determinant
Determinant

Reputation: 4036

How to declare a table class that contains multi-column primary key?

The columns of the primary key must be in specific order.

I see some code from document :

class User(Base):
    __tablename__ = 'users'

    id = Column(Integer)

    __mapper_args__ = {
        'primary_key':[id]
    }

But it just does not work (I'm using mysql, and the id primary key will not be generated). Any possible solutions?

Upvotes: 59

Views: 60399

Answers (1)

Denis Otkidach
Denis Otkidach

Reputation: 33200

In case columns are declared in the same order as they should be in the primary key:

class User(Base):
    field1 = Column(Integer, primary_key=True)
    field2 = Column(Integer, primary_key=True)

Otherwise declare it in __table_args__:

class User(Base):
    field1 = Column(Integer)
    field2 = Column(Integer)
    __table_args__ = (
        PrimaryKeyConstraint(field2, field1),
        {},
    )

Upvotes: 97

Related Questions