简体   繁体   中英

How to make auto increment field in django which starts from 10000

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 ?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM