我正在尝试使用复合主键创建一个表。它有一个整数和两个字符串字段作为键。当我提交会话时,它会引发IntegrityError
。我在做什么有什么问题?
class Targets(db.Model):
__tablename__ = 'Targets'
id = db.Column(db.Integer, primary_key=True)
Event_Name = db.Column(db.String, index=True, default='Single_Trigger', primary_key=True)
Trigger_id = db.Column(db.String, index=True, unique=True, primary_key=True)
>>> from app import db, models
>>> target = models.Targets(Trigger_id='20150421_221942_ST_1')
>>> db.session.add(target)
>>> db.session.commit()
IntegrityError: (IntegrityError) NOT NULL constraint failed: Targets.id u'INSERT INTO "Targets" ("Event_Name", "Name", "Trigger_id", "Tile", "Status", "RA", "Dec", "Filter", "Exp_time", "No_Exp") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)' ('Single_Trigger', '20150421_221942_ST_1', '20150421_221942_ST_1', 1, 0, 102.0, 231.25, 'V', 30, 5)
答案 0 :(得分:0)
SQLAlchemy没有在复合键上设置自动增量,你需要在id列上设置autoincrement = True。
如果表具有由多个整数列组成的复合主键,则仅在应被视为“自动增量”的列上将此标志设置为True。
答案 1 :(得分:0)
您必须在主键中显式设置autoincrement=True
:
class Targets(db.Model):
__tablename__ = 'Targets'
id = db.Column(db.Integer, primary_key=True)
Event_Name = db.Column(db.String, index=True, default='Single_Trigger', primary_key=True)
Trigger_id = db.Column(db.String, index=True, unique=True, primary_key=True)
重要的是,您必须降级到以前的迁移,删除迁移并创建新迁移并升级到该迁移。