如何在 Django 中制作数据库转储文件 [英] How to make db dumpfile in django
问题描述
无论我使用什么数据库,我都想在 django 中进行转储,并且可以稍后加载.命令 'dumpdata' 非常适合这个,但它在控制台上打印输出.此外,我使用 call_command 函数调用它,因此我无法将其内容存储在任何变量中,因为它在控制台上打印输出.
I want to make a dump in django irrespective of database I am using and can be loaded later. The command 'dumpdata' is perfect for this, but it is printing output on console. More over I am calling it using call_command function so I cannot store its content in any variable as it is printing output on console.
请告诉我如何使用 dumpdata 或任何其他命令或 API 将转储存储到文件中.
Please let me know how store dump to a file using dumpdata or any other command or api.
谢谢
推荐答案
如果你使用 call_command
call_command在 Python 中调用它,你可以选择一个文件来存放 dumpdata 的输出代码>,例如:
You can choose a file to put the output of dumpdata into if you call it from within Python using call_command
, for example:
from django.core.management import call_command
output = open(output_filename,'w') # Point stdout at a file for dumping data to.
call_command('dumpdata','model_name',format='json',indent=3,stdout=output)
output.close()
但是,如果您尝试从命令行调用它,例如--stdout=filename.json
在 dumpdata 命令的末尾,它给出了错误 manage.py: error: no such option: --stdout
.
However, if you try calling this from the command line with e.g. --stdout=filename.json
at the end of your dumpdata command, it gives the error manage.py: error: no such option: --stdout
.
所以它就在那里,您只需要在 Python 脚本中而不是在命令行中调用它.如果您希望将其作为命令行选项,那么重定向(正如其他人所建议的那样)是您最好的选择.
So it is there, you just have to call it within a Python script rather than on the command line. If you want it as a command line option, then redirection (as others have suggested) is your best bet.
这篇关于如何在 Django 中制作数据库转储文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!