Django + PostgreSQL: How to reset primary key?
In your app directory try this:
python manage.py help sqlsequencereset
Pipe it into psql like this to actually run the reset:
python manage.py sqlsequencereset myapp1 myapp2 | psql
Edit: here's an example of the output from this command on one of my tables:
BEGIN;SELECT setval('"project_row_id_seq"', coalesce(max("id"), 1), max("id") IS NOT null) FROM "project_row";COMMIT;
As suggested by "Van Gale" you can get the commands to solve your problem running sqlsequencereset
.
or
You can execute the SQL query generated by sqlsequencereset
from within python in this way (using the default database):
from django.core.management.color import no_stylefrom django.db import connectionfrom myapps.models import MyModel1, MyModel2sequence_sql = connection.ops.sequence_reset_sql(no_style(), [MyModel1, MyModel2])with connection.cursor() as cursor: for sql in sequence_sql: cursor.execute(sql)
I tested this code with Python3.6, Django 2.0 and PostgreSQL 10.
If you perform a raw sql, can do this:
ALTER SEQUENCE youApp_id_seq RESTART WITH 1;
docs:http://www.postgresql.org/docs/8.2/static/sql-altersequence.html