简体   繁体   中英

Automatically Load Django Fixture

I'm running Django 1.7. My file tree for the project is as such:

/project/app/fixtures/initial_data.json
/project/app/settings.py

I know I can run the python manage.py loaddata app/fixtures/initial_data.json command that will work for populating my database but I want to load it automatically when python manage.py migrate is run. My settings include:

FIXTURE_DIRS = (
    os.path.join(BASE_DIR, '/app/fixtures/'),
)

But the fixture is not applied when migrate is run. What seems to be the problem?

I'm afraid not and this is not your problem, because this is deprecated since Django 1.7:

READ HERE

Automatically loading initial data fixtures¶

Deprecated since version 1.7: If an application uses migrations, there is no automatic loading of fixtures. Since migrations will be required for applications in Django 1.9, this behavior is considered deprecated. If you want to load initial data for an app, consider doing it in a data migration.

If you create a fixture named initial_data.[xml/yaml/json], that fixture will be loaded every time you run migrate. This is extremely convenient, but be careful: remember that the data will be refreshed every time you run migrate. So don't use initial_data for data you'll want to edit.

If you really want this to work, you can always customise your manage.py ,

# import execute_from_command_line
    from django.core.management import execute_from_command_line

    # add these lines for loading data
    if len(sys.argv) == 2 and sys.argv[1] == 'migrate':
        execute_from_command_line(['manage.py', 'loaddata'])

    execute_from_command_line(sys.argv)

Hope this helps.

Sadly not enough points to be able to comment! This post is quite old... (Django 1.7 - 1.9)
Changing Manage.py is still a valid option to go!

  • A reminder to change "migrate" to "makemigrations"

if len(sys.argv) == 2 and (sys.argv[1] == 'makemigrations'):

Plus, for the people who don't often read the comments, add your JSON file to the "execute_from_command_line" function.

execute_from_command_line(['manage.py', 'loaddata', 'YourFileName.json'])

This way by running python manage.py makemigrations it will automatically load your fixture data stated in that file given hard-coded.

Needless to mention, every time you run that command it will override any data modification made to the models in that fixture.

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