Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer field not autoincrementing in SQLAlchemy

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?

like image 731
serverpunk Avatar asked Jan 01 '26 03:01

serverpunk


1 Answers

Use Sequence instead of autoincrement:

id = db.Column(db.Integer, db.Sequence("seq_street_segment_id"))
like image 53
univerio Avatar answered Jan 03 '26 16:01

univerio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!