如何使用call_command和dumpdata命令将json保存到文件 [英] How to use call_command with dumpdata command to save json to file

查看:160
本文介绍了如何使用call_command和dumpdata命令将json保存到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用 call_command 方法调用dumpdata 命令。手动,我使用它如下将数据保存到文件。

I am trying to use the call_command method to call the dumpdata command. Manually, I use it as follows to save the data to a file.

python manage.py dumpdata appname_one appname_two > /path/to/save/file.json

并保存json文件。现在,我处于这种情况,我需要使用 call_command 方法调用此命令。

and it saves the json file. Now, I am in a situation where I need to call this command using the call_command method.

使用以下命令从命令打印json:

I am able to print out the json from the command using the following:

from django.core.management import call_command

call_command('dumpdata', 'appname_one', 'appname_two')

推荐答案

必须重新导向 sys.stdout 到文件以实现上述。像

had to redirect sys.stdout to the file in order to achieve the above. Something like.

import sys

from django.core.management import call_command


sysout = sys.stdout
sys.stdout = open('filename.json', 'w')
call_command('dumpdata', 'appname_one', 'appname_two')
sys.stdout = sysout

这篇关于如何使用call_command和dumpdata命令将json保存到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆