DEV Community

fiona
fiona

Posted on • Edited on

5 1

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.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more