Skip to content

Instantly share code, notes, and snippets.

@yoandresaav
Last active March 1, 2026 21:39
Show Gist options
  • Select an option

  • Save yoandresaav/dba96969b239dfe7e45a51e77f28e2a5 to your computer and use it in GitHub Desktop.

Select an option

Save yoandresaav/dba96969b239dfe7e45a51e77f28e2a5 to your computer and use it in GitHub Desktop.
Fix error in pkey rests
The "Internal" Fix
Follow these steps to reset the counter using Python code:
Enter the Django Shell:
python manage.py shell
Run this script exactly:
Copy and paste this entire block into the shell. It will look at your data and force the counter to the correct next number.
from django.db import connection
def reset_sequence(table_name):
with connection.cursor() as cursor:
# This finds the max ID and sets the next value to max + 1
query = f"SELECT setval(pg_get_serial_sequence('{table_name}', 'id'), coalesce(max(id), 0) + 1, false) FROM {table_name};"
cursor.execute(query)
print(f"Reset sequence for {table_name}")
# Run it for your specific tables
# Note: Use the actual database table names (usually appname_modelname)
reset_sequence('your_table_to_reset')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment