Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
927 views
in Technique[技术] by (71.8m points)

sqlalchemy - 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?

question from:https://stackoverflow.com/questions/9034271/how-to-declare-a-table-class-that-contains-multi-column-primary-key

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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),
        {},
    )

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...