How to load initial_data (fixture) after migration and not after syncdb?
-
09-06-2021 - |
Question
I have a bootstrap
script that performs syncdb
and migrate
:
import settings
from django.core.management import setup_environ, call_command
setup_environ(settings) # Setting up the env settings
call_command('syncdb', migrate=True, interactive=False) # Sync the database
Pre-Requisites:
django-south
for migrations.
Process happening:
initial_data
fixture contains data for a model that is created by migrations.syncdb
is executed it creates all the tables except for those apps where migrations exists.- Post
syncdb
it tries to loadinitial_data
and raises error of db not found because the table for app with migrations were not created by syncdb. [ Problem ] - Then it performs migration which creates the db.
- Post
migration
it automatically loadsinitial_data
successfully this time.
Problem:
- How can I get rid of the
error
, when it tries to load fixture for the table that is not yet created ? - Can I edit the above script in a way so that it loads
initial_data
only after performing themigration
?
Solution
You could disable loading initial data when syncdb:
call_command('syncdb', load_initial_data=False, interactive=False)
call_command('migrate', interactive=False)
From the source code of syncdb.py:
# Stealth option -- 'load_initial_data' is used by the testing setup
# process to disable initial fixture loading.
load_initial_data = options.get('load_initial_data', True)
OTHER TIPS
There are a few ways you can solve this:
- Exclude the apps from the initial data dump by just calling the apps you want to populate data for
- Could try this library https://github.com/davedash/django-fixture-magic
- You could write a custom management command to populate the models you require
- You can also use data migration that comes with south http://south.aeracode.org/docs/tutorial/part3.html
Personally I would go with either 1 or 3. With the first point, store the fixtures individually in each app under a fixtures folder. However, this is pain to update if your models change. So writing a custom management command might be the most painless.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow