reset id model autoincrement

Even after using Entry.objects().all().delete() for clearing a Django model, the autoincremented primary key for the model is kept and new records keep the order accordingly. How could I do in the file to reset the id counter after clearing all the table model?


Whether or not you can do it in a view somewhat depends upon which database you’re using. For example, in PostgreSQL, the autoincrement value is stored in a database “sequence” object.
You would need to write raw SQL to do this to alter the sequence value for that field.

However, I’ll point out from a database perspective, it should never be necessary to do this. If you’re concerned about the primary key starting out at 1, you’re wasting mental energy worrying about something that shouldn’t be a concern. A numeric primary key of a table should have no semantic meaning - not even to identify sequencing.

1 Like

Perfectly explained, thanks a lot.
I was thinking about it because I wanted to arrange the records according to the moment when they were introduced. Probably it would be better to use a DateTimeField with auto_now right?

Absolutely. There is no guarantee that the autoincrement field maintains insertion-order.