Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django + PostgreSQL: How to reset primary key?

I have been working on an application in Django. To begin with, for simplicity, I had been using sqlite3 for the database.

However, once I moved to PostgreSQL, I've run into a bit of a problem: the primary key does not reset once I clear out a table.

This app is a game that is played over a long time period (weeks). As such, every time a new game starts, all of the data is cleared out of the database and then new, randomized data is added.

I'd like to be able to "start over" with primary keys starting at 1 each time I clean/rebuild the game.

The code still works as-is, but integers are a pretty natural way for describing the objects in my game. I'd like to have each new game start at 1 rather than wherever the last game left off.

How can I reset the primary key counter in PostgreSQL? Keep in mind that I don't need to preserve the data in the table since I am wiping it out anyway.

like image 773
TM. Avatar asked Feb 13 '09 05:02

TM.


People also ask

How do I change primary key in Django model?

If you'd like to specify a custom primary key, specify primary_key=True on one of your fields. If Django sees you've explicitly set Field.primary_key , it won't add the automatic id column. Each model requires exactly one field to have primary_key=True (either explicitly declared or automatically added).

Can we update primary key in PostgreSQL?

To change the primary key of a table, delete the existing key using a DROP clause in an ALTER TABLE statement and add the new primary key. Note You must be logged in to the database using a database name before you can add a primary key or conduct any other referential integrity (RI) operation.

Can Django model have two primary keys?

Do Django models support multiple-column primary keys? ¶ No. Only single-column primary keys are supported.


1 Answers

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; 
like image 138
Van Gale Avatar answered Sep 23 '22 02:09

Van Gale