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
Hiding Axis Text in Matplotlib Plots
How to Properly Setup Pipenv in Pycharm
How to Flatten a Hierarchical Index in Columns
Printing Simple Diamond Pattern in Python
Convert a Python Int into a Big-Endian String of Bytes
How to Display Index During List Iteration With Django
Pythonic Way to Find Maximum Value and Its Index in a List
Optimal Way to Store Data from Pandas to Snowflake
Check If List Is Ascending or Descending (Using For)
Pythonically Add Header to a CSV File
How to Print Just the First Letters of Each Word
How to Read Image Data from a Url in Python
Python Sockets Multiple Messages on Same Connection
How to Pass a .Txt File to a Function in Python
Fastest Way to Compute Image Dataset Channel Wise Mean and Standard Deviation in Python
Making Python Dictionary from a Text File With Multiple Keys