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?
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