Programmatically using Django's loaddata
Asked Answered
M

1

58

I'd like to call the equivalent of manage.py loaddata from a Django view. I'd like to be able to specify where to load the data from and which application to load it into.

Any ideas?

Madigan answered 20/5, 2009 at 12:29 Comment(0)
W
87

Each django-admin.py (manage.py) command, as seen in the documentation, you can call from your code with:

from django.core.management import call_command

call_command('loaddata', 'myapp')

Where first param is the command name, all other position params are the same as command line position params and all keyword params are options.

Westbrook answered 20/5, 2009 at 13:24 Comment(4)
you can also add option "verbosity=0" for supression console output: call_command('loaddata', 'fixture_name.json', verbosity=0)Refurbish
Docs here: docs.djangoproject.com/en/1.8/ref/django-admin/…Unsought
Please notice that it is not suitable to use loaddata command directly in a data migration, because it internally loads the most up-to-date model definitions and uses them to deserialize historical data in a fixture. That's incorrect behavior. Solution here: https://mcmap.net/q/204333/-loading-initial-data-with-django-1-7-and-data-migrationsIntermix
Also notice that you should use the app_label keyword argument to specify where to load the fixture, e.g. call_command('loaddata', 'initial_data.json', app_label='myapp'). Otherwise, it will load fixtures with the same name from all installed apps.Intermix

© 2022 - 2024 — McMap. All rights reserved.