Django 为自定义数据转储输入 call_command 的参数

Django entering args for call_command for custom datadump

我正在尝试为 Django 设备创建自定义数据转储,因此我不会将所有内容都转储到一个文件中。

这是我的代码抛出错误:

extract.py

def create_fixture( filename, *app_name):
    # buffer
    buf = StringIO()
    # unpacks args to list of db tables
    apps = ','.join(map(str, app_name))
    # calls dump data and adds db table to call command
    call_command('dumpdata', apps, indent=2, format='json', stdout=buf)
    # Write to file
    buf.seek(0)
    with open(Path.cwd().joinpath('main', 'fixtures', filename), 'w') as f:
        f.write(buf.read())

class Command(BaseCommand):
    help = 'Dumps database file to fixtures'

    def handle(self, *args, **kwargs):
        #calls function
        create_fixture('country.json','main.Country','main.Cities')
        #prints to console if successful
        self.stdout.write("Dumped Country data!")

如果我在控制台中 运行 python manage.py extract 我收到以下消息:

CommandError: No installed app with label 'main.Country,main.Cities'

但是如果我这样写代码它工作正常但不使用函数:

class Command(BaseCommand):
    help = 'Dumps database file to fixtures'

    def handle(self, *args, **kwargs):
        buf = StringIO()
        call_command('dumpdata', 'main.Country', 'main.Cities',indent=2, format='json', stdout=buf)
        buf.seek(0)
        with open(Path.cwd().joinpath('main', 'fixtures', 'country.json'), 'w') as f:
            f.write(buf.read())
        self.stdout.write("Dumped Country data")

不确定如何正确解压参数并将它们放入 call_command 函数

app_name 你传入的 create_fixture 是元组。 您不需要解压它们并转换为字符串。

当你这样做时:

apps = ','.join(map(str, app_name))

您实际上是先将其转换为列表,然后使用 (逗号)连接其所有元素。这只是给你一个字符串 'main.Country,main.Cities'

把你的元组直接传到顶部call_command.

call_command('dumpdata', *app_name, indent=2, format='json', stdout=buf)