57

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?

Deniz Dogan
  • 25,711
  • 35
  • 110
  • 162

1 Answers1

85

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.

pyjavo
  • 1,598
  • 2
  • 23
  • 41
Alex Koshelev
  • 16,879
  • 2
  • 34
  • 28
  • 5
    you can also add option "verbosity=0" for supression console output: call_command('loaddata', 'fixture_name.json', verbosity=0) – Sergey Telminov Mar 16 '15 at 18:55
  • 1
    Docs here: https://docs.djangoproject.com/en/1.8/ref/django-admin/#running-management-commands-from-your-code – Renato Jun 02 '15 at 18:15
  • 1
    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: http://stackoverflow.com/a/39743581/2293304 – Rockallite Oct 08 '16 at 02:15
  • 8
    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_. – Rockallite Oct 08 '16 at 02:26