Reset id count after table delete()

不打扰是莪最后的温柔 提交于 2019-12-06 05:39:54

问题


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


回答1:


Call TRUNCATE TABLE MyTable RESTART IDENTITY; for every table in the loop instead of calling table.delete() - this should reset the auto increment sequence.



来源:https://stackoverflow.com/questions/23038422/reset-id-count-after-table-delete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!