1

I have a pg database created by migrate with Django, all the tables have been created successfully and are empty at the start.

Now I have to fill one of the tables from a database backup created by pgdump. This database has a table transactions which contains data (consider no FK, and the schema of the table is same), so using pgrestore, I restored only that transaction table from the database backup. Everything restored and data is shown in the Django web app as well.

But Now when I create a new entry in that table using django web app, the django starts assigning the primary key from 1 to the newly created entry, but as the table is restored from a database backup, that id already exists, if I try again, django will try to assign PK 2, then 3 and so on. But those transactions have already been restored from DB backup

How to tell Django the last transaction id so that it can start assigning from there?

  • 1
    Django does not dispatch primary keys, you will need to look to the sequence in your postgreSQL database and set the start of the index of that primary key to a different value. – Willem Van Onsem Jun 13 '22 at 06:09
  • 1
    Thanks! I had no idea how to do that, but considering your suggestion and a little googling, I resolved the problem. I restarted the sequence from the last id +1 using `ALTER SEQUENCE public.transaction_id_seq RESTART 156098` , and it works fine now. Thanks again – Nitin sharma Jun 13 '22 at 06:57
  • 1
    https://stackoverflow.com/questions/244243 –  Jun 13 '22 at 06:58

1 Answers1

1

Django does not decide how the primary keys are generated for an AutoField [Django-doc] (or BigAutoField [Djang-doc] or SmallAutoField [Django-doc]): it is the database that assigns values for these.

For PostgreSQL, the database makes use of sequences, and each time it has to determine a value it updates the sequence, such that next time a different value will be given. You thus need to update that sequence.

As you found out yourself, you can do this with:

ALTER SEQUENCE public.modelname_id_seq RESTART some_value
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555