DEV Community

fiona
fiona

Posted on • Updated on

Django: reset auto-increment id to 1

The discussion in stackoverflow here gave a clear view of how to handle the problem, which many argue and I do agree that the id should not be reset since it is unique and should not be recreated.

Anyway, for the clarity of my database id, I still tend to do so. Simply erase table data from SQLiteStudio, or run objects.all().delete() does not reset the id. The answer provided in the above stackoverflow for sqlite is to run a sql command

-- reset index

DELETE FROM <table_name>; 
DELETE FROM SQLite_sequence WHERE name='<table_name>';
Enter fullscreen mode Exit fullscreen mode

UPDATE:
It also works when adding data to table with existing data.
In a senario where you import the wrong data, you can remove the data by the following:

-- delete certain rows (only keep rows that are between)

DELETE FROM <table_name>
WHERE id NOT IN (SELECT id FROM <table_name> WHERE id BETWEEN <int> AND <int>)
Enter fullscreen mode Exit fullscreen mode

Then run the previous reset index command to let the index remain consistent before import another data.

Top comments (0)