Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

django - How to reset the sequence for IDs on PostgreSQL tables

I recently imported a lot of data from an old database into a new Postgresql database as the basis for models in a new Django site.

I used the IDs from the old database (as rows in various tables refer to each other), but they aren't all sequential - there are often large gaps.

I've noticed that when I add a new object via the Django app, then it has been using IDs starting from 1, which hasn't been a problem so far as there were no rows with very low IDs.

But once it reaches the first row of legacy data, then postgres obviously complains:

ERROR:  duplicate key value violates unique constraint "django_comments_pkey"
DETAIL:  Key (id)=(25) already exists.

Looking at the table descriptions I'm guessing I need to reset some kind of sequence on each table:

                                      Table "public.django_comments"
     Column      |           Type           |                          Modifiers                           
-----------------+--------------------------+--------------------------------------------------------------
 id              | integer                  | not null default nextval('django_comments_id_seq'::regclass)
...

What do I need to do to reset that sequence, so that new rows are added with IDs higher than the current maximum ID?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Run sqlsequencereset and it'll print all the reset commands you need.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...