Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django reset auto-increment pk/id field for production

(I'm new to Django, Python, and Postgresql) I've been adding and deleting data in my development and noticed that the pk keeps adding up and never reset to 1 even if I delete all the models. Is it possible to reset the pk to start from 1 before I push this up to the production? Is it a good idea to do that?

like image 729
Vicky Leong Avatar asked Sep 11 '15 20:09

Vicky Leong


2 Answers

You can reset model id sequence using sqlsequencereset command

python manage.py sqlsequencereset myapp1 myapp2 myapp3| psql

If you want to read the generated sql command, just execute that command without pipe it to psql.

python manage.py sqlsequencereset myapp1 myapp2 myapp3

You need use this command over your production database. But, as @knbk mentioned, if your production database is new, you don't need to reset id sequences.

like image 144
levi Avatar answered Sep 27 '22 22:09

levi


Alternative to sqlsequencereset: Update directly with SQLite

Development Environnement with the default db.sqlite3 database

I was struggling for some time trying the answers given here and I kept receiving :

python manage.py sqlsequencereset AppName
>> No sequences found.

The easiest workaround for me was to directly update my SQLite database (i run my app locally):

# Open your database
sqlite3 db.sqlite3

And, in the SQLite prompt:

UPDATE sqlite_sequence SET seq = 0 WHERE sqlite_sequence.name = "<AppName_ModelName>";

I set the value to zero so it starts with id = 1.

EDIT : This is my very first post, please let me know if I should improve the format!

like image 23
Michael Debétaz Avatar answered Sep 27 '22 23:09

Michael Debétaz