4

I need an answer for this, right now im doing this command:

python manage.py loaddata app/myapp/fixtures/* --settings=setting.develop

This works fine, but now i want to do this same command but ignoring or skiping a simple file inside app/myapp/fixtures/ so i don't want to write one loaddata for every fixture inside, i wanted to make only one command and use something like --exclude or --ignore or some kind of way to do it in one line and keep the /* to go agains all the files inside.

Thanks in advance!

C. Herrera
  • 71
  • 1
  • 8
  • I don't believe there's any such exclude or ignore options for `loaddata`. Perhaps you could just combine all the fixtures you want to include into one larger fixture and just import it by name? – Fiver Feb 12 '16 at 22:50
  • Depending on your exact use case, you may be inclined to automate the [`loaddata`](https://docs.djangoproject.com/es/1.9/ref/django-admin/#loaddata) for the fixtures you want either with a shell script, or your own management command that uses [`call_command`](https://docs.djangoproject.com/es/1.9/ref/django-admin/#running-management-commands-from-your-code). – tutuDajuju Feb 15 '16 at 21:07

1 Answers1

3

Writing your own management command in Django is simple; and inheriting from Django's loaddata command makes it trivial:

excluding_loaddata.py

from optparse import make_option

from django.core.management.commands.loaddata import Command as LoadDataCommand


class Command(LoadDataCommand):
    option_list = LoadDataCommand.option_list + (
        make_option('-e', '--exclude', action='append',
                    help='Exclude given fixture/s from being loaded'),
    )

    def handle(self, *fixture_labels, **options):
        self.exclude = options.get('exclude')
        return super(Command, self).handle(*fixture_labels, **options)

    def find_fixtures(self, *args, **kwargs):
        updated_fixtures = []
        fixture_files = super(Command, self).find_fixtures(*args, **kwargs)
        for fixture_file in fixture_files:
            file, directory, name = fixture_file

            # exclude a matched file path, directory or name (filename without extension)
            if file in self.exclude or directory in self.exclude or name in self.exclude:
                if self.verbosity >= 1:
                    self.stdout.write('Fixture skipped (excluded: %s, matches %s)' %
                                      (self.exclude, [file, directory, name]))
            else:
                updated_fixtures.append(fixture_file)
        return updated_fixtures

usage:

$ python manage.py excluding_loaddata app/fixtures/* -e not_this_fixture
tutuDajuju
  • 10,307
  • 6
  • 65
  • 88