Django data initialization method

Development often encounter some of the data will exist in the database at runtime of the program, so we need to do the initial data. Here are two ways to initialize a simple data sharing Django.

Background: Project app: role has two mode: RoleType and UserRole, modol already written initialization method: init_builtin_roles()andinit_builtin_user_roles()

First, the use of file migrations

  • 1. Create a file migrations
 python manage.py makemigrations --empty role

Where role is the name of the app

Files are generated as shown below:

  • 2, in the preparation method of generating initialization data file
def init_data(apps, schema_editor):
    try:
        RoleType.init_builtin_roles()
        UserRole.init_builtin_user_roles()
    except Exception as e:
        logger.error(u'数据初始化error:{}'.format(e))

Then call the initialize method in operations in:

operations = [
        migrations.RunPython(init_data)
    ]

Finally generated file as shown below:

  • 3, the implementation python manage.py migratecan be completed initialization data

Second, the use of the signal post_migrate AppConfig

  • 1, in the app: Create a role apps.py file folder, write data initialization method in apps.py in:
def app_ready_handler(sender, **kwargs):
    from models import RoleType, UserRole
    print 'init builtin roles and user roles data'
    try:
        RoleType.init_builtin_roles()
        UserRole.init_builtin_user_roles()
    except Exception as e:
        print 'init builtin roles and user roles data exception: %s' % e

  • 2, inherited AppConfig create RoleConfig, in ready()using the signal method post_migrateto invoke the initialization method:

Signal post_migrate : After performing migrate command, automatically triggers

  • 3, Configuration default_app_config: Django will automatically go AppConfig By default, if there are changes need to be reconfigured.

In the following role _init_.pyprofiledefault_app_config

  • 4, the final implementation python manage.py migratecan be.

Guess you like

Origin www.cnblogs.com/wangyingblock/p/12668463.html