Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 373
Peter Graham Avatar asked Jan 06 '15 22:01

Peter Graham


People also ask

How do I use fixtures in Django?

Providing data with fixtures The most straightforward way of creating a fixture if you've already got some data is to use the manage.py dumpdata command. Or, you can write fixtures by hand; fixtures can be written as JSON, XML or YAML (with PyYAML installed) documents.

What is fixture file in Django?

The Feature file consists of statements written in plain English that describe how to configure, execute, and confirm the results of a test. Use the Feature keyword to label the feature and the Scenario keyword to define a user story that you are planning to test.

What command line is used for loading data in Django?

Ans: To load data into Django you have to use the command line Django-admin.py loaddata. The command line will searches the data and loads the contents of the named fixtures into the database.


1 Answers

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.

like image 124
Anzel Avatar answered Sep 28 '22 07:09

Anzel