Django reset auto-increment pk/id field for production

17,935

Solution 1

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.

Solution 2

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!

Share:
17,935

Related videos on Youtube

Vicky Leong
Author by

Vicky Leong

Updated on June 18, 2022

Comments

  • Vicky Leong
    Vicky Leong almost 2 years

    (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?

    • knbk
      knbk over 8 years
      If production is a new database, you won't need to reset it.
  • Vicky Leong
    Vicky Leong over 8 years
    I see. I may not do that then since the db will be new. Thanks also, @knbk and jlnbais
  • flyingfishcattle
    flyingfishcattle about 3 years
    works great, shouldn't the "<AppName_ModelName>" be the database table name?
  • Michael Debétaz
    Michael Debétaz about 3 years
    It is indeed. The table name, on my version of Django (3.1.7) and with SQLite at least, is named by concatenation of the name of your app and the name of the model you are targetting. For example, I created a model for "engine" to monitor with my "dashboard" app, so my target table's name is "dashboard_engine".
  • Cornel Ciobanu
    Cornel Ciobanu over 2 years

Related