djangoprimary-keymodelsinstances

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


I have been working on an offline version of my Django web app and have frequently deleted model instances for a certain ModelX.

I have done this from the admin page and have experienced no issues. The model only has two fields: name and order and no other relationships to other models.

New instances are given the next available pk which makes sense, and when I have deleted all instances, adding a new instance yields a pk=1, which I expect.

Moving the code online to my actual database I noticed that this is not the case. I needed to change the model instances so I deleted them all but to my surprise the primary keys kept on incrementing without resetting back to 1.

Going into the database using the Django API I have checked and the old instances are gone, but even adding new instances yield a primary key that picks up where the last deleted instance left off, instead of 1.

Wondering if anyone knows what might be the issue here.


Solution

  • As others have stated, this is entirely the responsibility of the database.

    But you should realize that this is the desirable behaviour. An ID uniquely identifies an entity in your database. As such, it should only ever refer to one row. If that row is subsequently deleted, there's no reason why you should want a new row to re-use that ID: if you did that, you'd create a confusion between the now-deleted entity that used to have that ID, and the newly-created one that's reused it. There's no point in doing this and you should not want to do so.