Django model instances primary keys do not reset to 1 after all instances are deleted

I wouldn’t call it an issue. This is default behaviour for many database systems. Basically, the auto-increment counter for a table is persistent, and deleting entries does not affect the counter. The actual value of the primary key does not affect performance or anything, it only has aesthetic value (if you ever reach the 2 billion limit you’ll most likely have other problems to worry about).

If you really want to reset the counter, you can drop and recreate the table:

python manage.py sqlclear <app_name> > python manage.py dbshell

Or, if you need to keep the data from other tables in the app, you can manually reset the counter:

python manage.py dbshell
mysql> ALTER TABLE <table_name> AUTO_INCREMENT = 1;

The most probable reason you see different behaviour in your offline and online apps, is that the auto-increment value is only stored in memory, not on disk. It is recalculated as MAX(<column>) + 1 each time the database server is restarted. If the table is empty, it will be completely reset on a restart. This is probably very often for your offline environment, and close to none for your online environment.

Leave a Comment

tech