DEV Community

Shakhzhakhan Maxudbek
Shakhzhakhan Maxudbek

Posted on • Edited on • Originally published at args.tech

Reset autoincrement sequences for IDs in Django application after all instances are deleted (PostgreSQL)

After deletion entries in your model relational database management systems not resetting autoincrementations and continue counting old IDs sequences. For start counting entries from 1 again you need reset sequence manually.

Django's autogenerated manage.py script have argument named "sqlsequencereset". It helps to reset autoincrement sequences for IDs in Django application after all instances in model are deleted. Documentation say:

django-admin sqlsequencereset app_label [app_label ...]
Prints the SQL statements for resetting sequences for the given app name(s).
Sequences are indexes used by some database engines to track the next available number for automatically incremented fields.
Use this command to generate SQL which will fix cases where a sequence is out of sync with its automatically incremented field data.
--database DATABASE
Specifies the database for which to print the SQL. Defaults to default.
Enter fullscreen mode Exit fullscreen mode

Navigate in your application's workdir, activate virtual environment and run command for resetting sequences:

python manage.py sqlsequencereset <application_name> | python manage.py dbshell
Enter fullscreen mode Exit fullscreen mode

Additionally PostgreSQL have equivalent command. Enter in psql shell and run:

sudo -u postgres psql
postgres=# ALTER SEQUENCE <application_name>_<model_name>_id_seq RESTART WITH 1;
Enter fullscreen mode Exit fullscreen mode

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay