unable to create autoincrementing primary key with flask-sqlalchemy unable to create autoincrementing primary key with flask-sqlalchemy flask flask

unable to create autoincrementing primary key with flask-sqlalchemy


Nothing is wrong with the above code. In fact, you don't even need autoincrement=True or db.Sequence('seq_reg_id', start=1, increment=1), as SQLAlchemy will automatically set the first Integer PK column that's not marked as a FK as autoincrement=True.

Here, I've put together a working setup based on yours. SQLAlechemy's ORM will take care of generating id's and populating objects with them if you use the Declarative Base based class that you've defined to create instances of your object.

from flask import Flaskfrom flask.ext.sqlalchemy import SQLAlchemyapp = Flask(__name__)app.debug = Trueapp.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://user:password@localhost/testdb'app.config['SQLALCHEMY_ECHO'] = Truedb = SQLAlchemy(app)class Region(db.Model):    __tablename__ = 'regions'    id = db.Column(db.Integer, primary_key=True)    name = db.Column(db.String(100))db.drop_all()db.create_all()region = Region(name='Over Yonder Thar')app.logger.info(region.id) # currently None, before persistencedb.session.add(region)db.session.commit()app.logger.info(region.id) # gets assigned an id of 1 after being persistedregion2 = Region(name='Yet Another Up Yar')db.session.add(region2)db.session.commit()app.logger.info(region2.id) # and 2if __name__ == '__main__':    app.run(port=9001)


I think you do not need the autoincrement once you set ,

id = db.Column(db.Integer , primary_key=True , autoincrement=True)

I think that it should be ,

id = db.Column(db.Integer , primary_key=True)

it will give you the uniqueness your looking for .


So I landed here with an issue that my SQLite table wasn't auto-incrementing the primary key. I have a slightly complex use case where I want to use postgres in production but sqlite for testing to make life a bit easier when continuously deploying.

It turns out SQLite doesn't like columns defined as BigIntegers, and for incrementing to work they should be set as Integers. Remarkably SQLAlchemy can handle this scenario as follows using the with_variant function. Thought this may be useful for someone:

id = db.Column(db.BigInteger().with_variant(db.Integer, "sqlite"), primary_key=True)

Further details here https://docs.sqlalchemy.org/en/13/dialects/sqlite.html