简体   繁体   中英

IntegrityError when inserting model with composite primary key

I am trying to create a table with composite primary keys. It has one integer and two string fields as the key. When I commit the session it raises an IntegrityError . What is wrong with what I am doing?

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)

SQLAlchemy doesn't set auto-increment on composite keys, you need to set autoincrement=True on the id column.

http://docs.sqlalchemy.org/en/latest/core/metadata.html#sqlalchemy.schema.Column.params.autoincrement

If the table has a composite primary key consisting of more than one integer column, set this flag to True only on the column that should be considered “autoincrement”.

Yo have to set autoincrement=True , explicit in the primary key:


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)

The important part is that you have to downgrade to the previous migration, delete the migration and create new one and upgrate to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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