我想创建一个格式为(date,id)的复合主键。我的代码目前看起来像这样
class Gyroinfo(Base):
__tablename__ = 'GYROINFO'
id = Column(Integer, primary_key=True,autoincrement = True)
date = Column(DateTime, primary_key = True)
,但这默认为格式(id,日期)的主键。如何切换主键顺序?
答案 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)