Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize sequence after deleting table, SQLAlchemy , Postresql

I am using a Postgres database with sqlalchemy in my Flask API, my database models are defined as follow:

 class Cache1(db.Model):
  __tablename__ = 'Cache1'
  id = db.Column(db.Integer, Sequence('Cache1_id_seq', start=1, increment=1), primary_key=True)
  name = db.Column(db.String(20))

The problem is when i do Cache1.query.delete() in one of my views and then i try to put new records in Cache1, the sequence number does not start from 1. I should always go to Postgres and do ALTER SEQUENCE "Cache1_id_seq" RESTART WITH 1. Can someone show me a way to do this in Sqlalchemy . Thank you in adcance

like image 980
Rzozi Avatar asked Mar 25 '16 09:03

Rzozi


1 Answers

Use the ALTER SEQUENCE command to modify PostgreSQL sequences. There is no built-in SQLAlchemy function for this, use session.execute to execute the SQL.

db.session.execute("ALTER SEQUENCE Cache1_id_seq RESTART WITH 1")
db.session.commit()
like image 66
Daniil Mashkin Avatar answered Oct 19 '22 21:10

Daniil Mashkin