How to get Django AutoFields to start at a higher number

前端 未结 7 734
挽巷
挽巷 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: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.

提交回复
热议问题