1

I have an existing django model in my project, and it's already in production database (PostgreSQL) and has records in it.

And what I basically want is to set id (autoincrement pk) of new created objects to have at least 5 digits and start from 5. So for example if I have last record in database with id 1924 I want my next object to have id 51925 (last id + 1 + 50000). So it will be like this:

older objects
...
1921
1922
1923
1924 # last in production
51925 # next object to be created must autoincrement from 50001 + previous id
51926
51927
.... and so on

Is it possible and what is the best way to do it? thanks

marzique
  • 635
  • 1
  • 7
  • 17
  • 2
    Use [`ALTER SEQUENCE ... RESTART WITH ;`](https://stackoverflow.com/a/118402/16361). You need to query for the previous max ID on your own, there's no syntax for saying 'start this sequence from the result of the expression "select max(id)+50000 from table"'. – AdamKG Apr 07 '21 at 16:44
  • @AdamKG thanks, so the previous records will still have existing ids? And only new ones will start from number I will specify? – marzique Apr 07 '21 at 16:46
  • Yes, that's correct. – AdamKG Apr 07 '21 at 16:50

1 Answers1

2

Thanks to @AdamGK comment I found this answer that helps to generate needed psql command:

python manage.py sqlsequencereset yourappname

After running it, I found line with model i needed (I changed app and model names for the sake of example):

SELECT setval(pg_get_serial_sequence('"yourappname_modelname"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "yourappname_modelname";

and then just changed it to (max id + 50000):

SELECT setval(pg_get_serial_sequence('"yourappname_modelname"','id'), coalesce(max("id") + 50000, 1), max("id") IS NOT null) FROM "yourappname_modelname";

And it worked like a charm!

marzique
  • 635
  • 1
  • 7
  • 17