Integer field not autoincrementing in SQLAlchemy

旧巷老猫 提交于 2019-12-13 02:12:11

问题


I have a Flask-SQLAlchemy model with an Integer field that I'd like to autoincrement. It's not a primary key; it's a surrogate ID. The model looks like:

class StreetSegment(db.Model):
    id = db.Column(db.Integer, autoincrement=True)
    seg_id = db.Column(db.Integer, primary_key=True)

When I create the table in my Postgres database, the id field is created as a plain integer. If I insert rows without specifying a value for id, it doesn't get populated. Is there some way I can force SQLAlchemy to use SERIAL even if it isn't the primary key?


回答1:


Use Sequence instead of autoincrement:

id = db.Column(db.Integer, db.Sequence("seq_street_segment_id"))


来源:https://stackoverflow.com/questions/35897254/integer-field-not-autoincrementing-in-sqlalchemy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!