如何使用 call_command 和 dumpdata 命令将 json 保存到文件 [英] How to use call_command with dumpdata command to save json to file
问题描述
我正在尝试使用 call_command
方法来调用转储数据 command
.手动,我使用它来将数据保存到文件中.
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')
有没有办法像我们从命令行那样将给定的数据保存到文件中?
Is there a way I can save the given data to a file like we do it from the command line?
推荐答案
必须将 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屋!