Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

django - How to use call_command with dumpdata command to save json to file

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

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...