问题
I'm using fixtures in my Django application but only two apps are getting their fixtures loaded.
When I manually run loaddata with --verbosity=2 I can see that it only looks in two apps although I have more with fixtures directories created inside.
All apps are correctly installed in settings.py.
From the documentation it seems that Django is supposed to search in the fixtures/ directory of every installed application.
Any ideas why some apps are ignored ?
回答1:
Initial_data gets imported each time you do syncdb. As fair as I remember, it also overwrites any changes you have done manually.
To load other fixtures, you have to use manage.py loaddata fixturename. That works well if you have you use a common naming scheme in all your apps. If you don't, you have to give loaddata the name of each one, or use find to get the list of fixtures and exec loaddata in each one of them:
EDIT: (as I add manage.py to /bin in the virtualenv when I install the django package I only use manage.py, if you don't you will need python manage.py loaddata of course)
find . -name "*.json" -exec manage.py loaddata {} \;
I use this in a fabfile to automate staging installations:
def load_all_fixtures():
"""Loads all the fixtures in every dir"""
with cd(env.directory):
run("""
source /usr/local/bin/virtualenvwrapper.sh &&
workon %s &&
find -L . -name "*.json" -exec manage.py loaddata {} \;
""" % env.virtualenv )
回答2:
Try calling this way
python manage.py loaddata initial_data
OR programmetically you can call it like
from django.core.management import call_command
call_command('loaddata', 'initial_data', verbosity=3, database='default')
回答3:
The problem is that Django only looks for fixtures in apps that provide a model. You probably have an app that has no model, but you still want to load some fixtures (maybe sample data for another installed app).
The culprit for this behavior in Django is get_apps()
in loaddata.py
:
- django.core.management.commands.loaddata, line 102
- django.db.models.loading, line 132
To trick Django into looking at your app's <app>/fixtures/
folder you have to add an (empty) models.py
file to the app. (Be nice and put a comment into that file to make things clear!)
<app>/models.py
"""
No real model, just an empty file to make Django load the fixtures.
"""
Afterwards, running python manage.py loaddata <fixture>
manually will find your app's fixture file.
回答4:
You have to place fixture data in initial_data.[json|xml,...] file.
I think that only those files are loaded by default.
appdir/fixtures/initial_data.json
来源:https://stackoverflow.com/questions/5167276/how-to-load-django-fixtures-from-all-apps