For testing purposes, I clear (delete) every table before executing code.
for table in reversed(db.metadata.sorted_tables):
engine.execute(table.delete())
do_stuff()
However, the new data's id values start from where the previous id's left off:
First iteration:
id | value
-----+---------
1 | hi
2 | there
Second iteration (delete table, insert new data):
id | value
-----+---------
3 | good
4 | day
Is there any way to reset the id count when I delete the table?
EDIT: seems I broke it, table is not cleared at all now
config.py
SQLALCHEMY_DATABASE_URI = 'postgresql://postgres:myPassword@localhost/myDatabase'
app.py
app = Flask(__name__)
app.config.from_pyfile('config.py')
db = SQLAlchemy(app)
models.py
from app import app, db
def clear():
for table in reversed(db.metadata.sorted_tables):
db.engine.execute('TRUNCATE TABLE ' + table.name + ' RESTART IDENTITY CASCADE')
The table is still being added to (using db.session.add_all() and db.session.commit()). However, clear() does nothing. When I log in as the postgres user in terminal and directly execute TRUNCATE TABLE myTable RESTART IDENTITY CASCADE, it works.
table.name gives the correct names. That leads me to believe there is something wrong with db.engine.execute(), but that does not make much sense since db.session.add_all() works
Call TRUNCATE TABLE MyTable RESTART IDENTITY; for every table in the loop instead of calling table.delete() - this should reset the auto increment sequence.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With