0

I have a User Model.

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), unique=True)

I created this table in the database and I had some users which I exported from old database and loaded this in this new table via insert query. but now when I try to create user using ORM like below

user = User(name="sanjay")
db.session.add(user)
db.session.commit()

it's throwing below error.

DETAIL:  Key (id)=(1) already exists

because a user with id 1 is already present in the table, so sqlalchemy should try to create a new record with latest id.

can someone help here?

Sanjay
  • 1,958
  • 2
  • 17
  • 25
  • For that u will need to set autoincrement, try this ```db.Column(db.Integer, primary_key=True, autoincrement=True)``` & make sure you enable the same in db table also. – sushanth May 21 '20 at 07:41
  • I tried with autoincrement also, but still same – Sanjay May 21 '20 at 07:47
  • Which DB your using ? – sushanth May 21 '20 at 07:51
  • I am using Postgres – Sanjay May 21 '20 at 07:53
  • 1
    U might need to update the autoincrement start value, https://kylewbanks.com/blog/Adding-or-Modifying-a-PostgreSQL-Sequence-Auto-Increment – sushanth May 21 '20 at 07:55
  • The sequence supplying the default primary key value does not track if you insert values manually in the table. It has to be updated to produce values that do not overlap with those inserted. See https://stackoverflow.com/questions/244243/how-to-reset-postgres-primary-key-sequence-when-it-falls-out-of-sync, https://stackoverflow.com/questions/40280158/postgres-sqlalchemy-auto-increment-not-working/40281835#40281835 – Ilja Everilä May 21 '20 at 09:19

0 Answers0