SQL Alchemy复合键顺序

时间:2018-07-18 16:44:08

标签: python sqlalchemy

我想创建一个格式为(date,id)的复合主键。我的代码目前看起来像这样

class Gyroinfo(Base):
    __tablename__ = 'GYROINFO'

    id = Column(Integer, primary_key=True,autoincrement = True)
    date = Column(DateTime, primary_key = True)

,但这默认为格式(id,日期)的主键。如何切换主键顺序?

1 个答案:

答案 0 :(得分:4)

我假设您在这里使用MySQL,所以如果不告诉我,我将删除此答案。

您可以阅读Mike Bayer关于使用MySQL here对主键字段进行重新排序的内容。以及SQLAlchemy如此行事的原因,here

您可以通过在PrimaryKeyConstraint字段中使用UniqueConstraint和单独的id来实现所需的目标。例如:

class Gyroinfo(Base):
    __tablename__ = 'GYROINFO'

    id = Column(Integer, autoincrement=True, unique=True)
    date = Column(DateTime)

    __table_args__ = (
        PrimaryKeyConstraint(date, id),
    )

哪个会产生以下sql:

CREATE TABLE `GYROINFO` (
        id INTEGER NOT NULL AUTO_INCREMENT,
        date DATETIME NOT NULL,
        PRIMARY KEY (date, id),
        UNIQUE (id)
)

unique=True字段定义中没有多余的id的情况下,SQLAlchemy发出一个CREATE TABLE,并按您希望的顺序排列列:

CREATE TABLE `GYROINFO` (
        id INTEGER NOT NULL AUTO_INCREMENT,
        date DATETIME NOT NULL,
        PRIMARY KEY (date, id)
)

但是它被MySQL拒绝了:

Incorrect table definition; there can be only one auto column and it must be defined as a key

但是,这引出了一个问题,即为什么根本需要在主键中使用date字段。由于id是自动递增的,因此它将在表的所有条目中都是唯一的,因此在date的复合字段中包含id不会增加任何额外的复杂性。我会坚持:

class Gyroinfo(Base):
    __tablename__ = 'GYROINFO'

    id = Column(Integer, autoincrement=True, primary_key=True)
    date = Column(DateTime, index=True)