[Django]-Reset primary key of Postgres database with Django

7👍

Postgres by default creates a new sequence for all columns created of the type serial. The default name of the django auth user is auth_user, so the default sequence name will be auth_user_id_seq or something like that.

You can find what the next sequence value is, by

SELECT nextval('auth_user_id_seq');

and you can set it to 1 by the following:

SELECT setval('auth_user_id_seq', 1);
👤lprsd

1👍

the easiest way to fix this problem (without dropping the entire database) is to connect to the database using either psql or a sql client (like this http://www.sqlmanager.net/en/products/postgresql/manager, there is a free light version). Then issue the following command:

truncate <user_table> reset identity

then you can repopulate the database

actually, you can actually also do this by using raw queries from django shell: https://docs.djangoproject.com/en/dev/topics/db/sql/#executing-custom-sql-directly

0👍

To reset everything, drop the database, the recreate it and run syncdb to re-create the tables.

To only reset the increment counter, this question should be helpful: How to reset postgres' primary key sequence when it falls out of sync?

The part you say about “when creating other tables that use User.id as the primary key, they are always 14 off.” is worrisome. You’re not relying on the auto-incremented primary keys on each table for a relation, are you?

👤JAL

Leave a comment