How Can My Model Primary Key Start With a Specific Number

How can my Model primary key start with a specific number?

the way is the same as to do datamigrations with RAW_SQL, change APPNAME on your:

python manage.py makemigrations APPNAME --empty

inside the created file:

operations = [
migrations.RunSQL(
'ALTER SEQUENCE APPNAME_USER_id_seq RESTART WITH 10000;'
)
]

How to make a primary key start from 1000?

If your table has already been created with an auto-increment. so you can use

ALTER TABLE tbl AUTO_INCREMENT = 1000;

otherwise put the AUTO_INCREMENT = 1000; in your CREATE TABLE

it goes before the final
);

How to make id (primary key) of new created objects start from some value?

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!

How to start Django models auto increment key from a certain number like 2456?

Create a RunSQL--(Django Doc) operation

from django.db import migrations


class Migration(migrations.Migration):
dependencies = [
('sample', '0003_content'),
]

operations = [
migrations.RunSQL(
"ALTER SEQUENCE sample_content_id_seq RESTART WITH 1453"
),
]

Django starting id with a specific number?

You can follow this answer

If this won't work then follow these step

>>> u = Projeto.objects.create()
>>> Projeto.objects.filter(pk=u.pk).update(id=10000)

In create method you may require to pass model mandatory fields with value like this

Projeto.objects.create(name='Test Project')


Related Topics



Leave a reply



Submit