1

I want to make an auto increment field in Django which starts from bigger value , I found use Autofield in models but It starts from 1 .

class University(models.Model):
    id = models.AutoField(primary_key=True)
    university_name = models.CharField(max_length=250, unique=True)
    university_slug = models.SlugField(max_length=250, unique=True)

    def __unicode__(self):
        return self.university_name

How can do this ? Any helpful suggestion will be appreciated ?

shuboy2014
  • 1,350
  • 2
  • 18
  • 44
  • Take a look at the second answer here: http://stackoverflow.com/questions/117800/how-to-get-django-autofields-to-start-at-a-higher-number since you appear to be using mysql – brianpck Sep 29 '16 at 20:14

2 Answers2

1

The simplest is to catch the post migrate signal

from django.apps import AppConfig
from django.db.models.signals import post_migrate

def my_callback(sender, **kwargs):
     if sender.name = 'myapp'
     try:
         university = University.objects.create(pk=999, ...)
         university.delete()
     except IntegrityError:
         pass

class MyAppConfig(AppConfig):
    ...

    def ready(self):
        post_migrate.connect(my_callback, sender=self)

What we are doing here is creating a record and deleting it immediately. On mysql that changes the next value in the auto increment. It doesn't matter that the record has been deleted. The next asigned number will be 1000.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
e4c5
  • 52,766
  • 11
  • 101
  • 134
  • I like this solution but I cannot get it to work. I added the code to `apps.py`, made a small change to my models and did `makemigrations` and `migrate` but it is not creating new records from 1000. What am I missing? – HenryM Jun 13 '18 at 13:18
  • I don't think this works with SQLite, does it? No matter how many records you had previously, if you delete them all and your table is empty, it will assign 1 as primary key to the first record created. @HenryM was probably using SQLite. Did anyone ever find a solution to this question though? – Quanta Jun 24 '20 at 08:16
  • This was not tagged as sqlite. Might i also suggest that you actually try it on sqlite – e4c5 Jun 24 '20 at 09:54
-1

Rather then trying in front end , I suggest you to create sequences in backend (in Database) with starting higher numbers Sequence value.

Hope this will solve your purposes.