Django 1.6:如何在python manage.py loaddata中忽略fixture?

4
我需要一个答案,现在我正在执行这个命令:
python manage.py loaddata app/myapp/fixtures/* --settings=setting.develop

这个命令很好用,但现在我想做同样的命令,但是忽略或跳过app/myapp/fixtures/中一个简单的文件,这样我就不需要为每个fixture编写一个loaddata,我希望只使用一个命令,并使用像--exclude或--ignore这样的方式在一行内完成,同时保留“/*”以针对所有文件。
提前感谢!

我不相信loaddata有任何排除或忽略选项。也许你可以将所有想要包含的fixture合并成一个更大的fixture,然后通过名称导入它? - Fiver
根据您的具体用例,您可能倾向于使用shell脚本或自己的管理命令来自动化loaddata以获取所需的fixture,并使用call_command运行该命令。 - tutuDajuju
1个回答

3
编写Django的自定义管理命令非常简单; 并继承Django的loaddata命令使其变得微不足道:

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

用法

$ python manage.py excluding_loaddata app/fixtures/* -e not_this_fixture

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接