简体   繁体   English

sqlalchemy ORM:如何声明包含多列主键的表类?

[英]sqlalchemy ORM : 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). 但它只是不起作用(我使用的是mysql,并且不会生成id主键)。 Any possible solutions? 任何可能的解决方

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__ : 否则在__table_args__声明它:

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

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

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