How to get Django AutoFields to start at a higher number

前端 未结 7 606
挽巷
挽巷 2020-12-02 19:15

For our Django App, we\'d like to get an AutoField to start at a number other than 1. There doesn\'t seem to be an obvious way to do this. Any ideas?

相关标签:
7条回答
  • 2020-12-02 19:44

    The auto fields depend, to an extent, on the database driver being used.

    You'll have to look at the objects actually created for the specific database to see what's happening.

    0 讨论(0)
  • 2020-12-02 19:50

    Like the others have said, this would be much easier to do on the database side than the Django side.

    For Postgres, it'd be like so: ALTER SEQUENCE sequence_name RESTART WITH 12345; Look at your own DB engine's docs for how you'd do it there.

    0 讨论(0)
  • 2020-12-02 19:51

    For MySQL i created a signal that does this after syncdb:

    from django.db.models.signals import post_syncdb
    from project.app import models as app_models
    
    def auto_increment_start(sender, **kwargs):
        from django.db import connection, transaction
        cursor = connection.cursor()
        cursor = cursor.execute("""
                                    ALTER table app_table AUTO_INCREMENT=2000
                                """)
        transaction.commit_unless_managed()
    
    post_syncdb.connect(auto_increment_start, sender=app_models)
    

    After a syncdb the alter table statement is executed. This will exempt you from having to login into mysql and issuing it manually.

    EDIT: I know this is an old thread, but I thought it might help someone.

    0 讨论(0)
  • 2020-12-02 19:59

    Here is what I did..

    def update_auto_increment(value=5000, app_label="remrate_data"):
        """Update our increments"""
        from django.db import connection, transaction, router
        models = [m for m in get_models() if m._meta.app_label == app_label]
        cursor = connection.cursor()
        for model in models:
            _router = settings.DATABASES[router.db_for_write(model)]['NAME']
            alter_str = "ALTER table {}.{} AUTO_INCREMENT={}".format(
                _router, model._meta.db_table, value)
            cursor.execute(alter_str)
            transaction.commit_unless_managed()
    
    0 讨论(0)
  • 2020-12-02 20:06

    I needed to do something similar. I avoided the complex stuff and simply created two fields:

    id_no = models.AutoField(unique=True)
    my_highvalue_id = models.IntegerField(null=True)
    

    In views.py, I then simply added a fixed number to the id_no:

    my_highvalue_id = id_no + 1200

    I'm not sure if it helps resolve your issue, but I think you may find it an easy go-around.

    0 讨论(0)
  • 2020-12-02 20:07

    I found a really easy solution to this! AutoField uses the previous value used to determine what the next value assigned will be. So I found that if I inserted a dummy value with the start AutoField value that I want, then following insertions will increment from that value.

    A simple example in a few steps:

    1.) models.py

    class Product(models.Model):
        id = model.AutoField(primaryKey=True) # this is a dummy PK for now
        productID = models.IntegerField(default=0)
        productName = models.TextField()
        price = models.DecimalField(max_digits=6, decimal_places=2)
    
    • makemigrations
    • migrate

    Once that is done, you will need to insert the initial row where "productID" holds a value of your desired AutoField start value. You can write a method or do it from django shell.

    From view the insertion could look like this: views.py

    from app.models import Product
    
    dummy = {
       'productID': 100000,
       'productName': 'Item name',
       'price': 5.98,
    }
    
    Products.objects.create(**product)
    

    Once inserted you can make the following change to your model:

    models.py

    class Product(models.Model):
        productID = models.AutoField(primary_key=True)
        productName = models.TextField()
        price = models.DecimalField(max_digits=6, decimal_places=2)
    

    All following insertions will get a "productID" incrementing starting at 100000...100001...100002...

    0 讨论(0)
提交回复
热议问题