[Fixed]-How can my Model primary key start with a specific number?

28👍

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;'
    )
]

1👍

The solution is to set autoincrement field like:

user_id = models.AutoField(primary_key=True)

After this, you can run this command on the database side. You can run this python command by using signals:

ALTER SEQUENCE user_id RESTART WITH 10000;

You can do this by different method.

from django.db.models.signals import post_syncdb
from django.db import connection, transaction
cursor = connection.cursor()
cursor = cursor.execute(""" ALTER SEQUENCE user_id RESTART WITH 10000; """)
transaction.commit_unless_managed()

post_syncdb.connect(auto_increment_start, sender=app_models)

In Django, a model can’t have more than one AutoField. And this is used to set a primary key different from the default key.

0👍

My solution is to do it manually:

$ ./manage.py shell
Python 3.6.5 (default, Apr  1 2018, 05:46:30)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.4.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: from django.contrib.auth.models import User

In [2]: u = User.objects.create_user('name', '', '')

In [3]: User.objects.filter(id=u.id).update(id=10000-1)
Out[3]: 1

In [4]: u.delete()
Out[4]:
(0,
 {'admin.LogEntry': 0,
  'auth.User_groups': 0,
  'auth.User_user_permissions': 0,
  'auth.User': 0})

In [5]: uu = User.objects.create_user('user', '', '')

In [6]: uu.id
Out[6]: 10000

0👍

For MySQL add this in your migration file:
Replace TABLE_NAME and START_VALUE with your table’s name and value with which you want to start.

operations = [        
        migrations.RunSQL('ALTER TABLE TABLE_NAME AUTO_INCREMENT=START_VALUE ;')
]

Leave a comment