How to make db dumpfile in django

天大地大妈咪最大 提交于 2019-12-03 15:14:36

问题


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.

Please let me know how store dump to a file using dumpdata or any other command or api.

Thanks


回答1:


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()

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.

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.




回答2:


You just use it like that:

./manage.py dumpdata > data_dump.json

After that action, there will be data_dump.json file in the directory in which you executed that command.

There are multiple options coming with that, but you probably already know it. The thing you need to know is how to redirect output from standard output into some file: you perform that action by putting > before file name.

To append something to the file you would use >>, but since you are dumping the data from Django and the output is most likely JSON, you will not want that (because it will make JSON invalid).




回答3:


django-admin.py dumpdata

Outputs to standard output all data in the database associated with the named application(s).

As you know, you can redirect standard output to a file:

command > file.data



回答4:


As it is mention in the docs, in order to dump large datasets you can avoid the sections causing problems, and treat them separately.

The following command does generally work:

python manage.py dumpdata --exclude auth.permission --exclude contenttypes > db.json

python manage.py loaddata db.json

In case you can export later the excluded data:

python manage.py dumpdata auth.permission > auth.json

python manage.py loaddata auth.json



回答5:


In Linux, you can just pipe the console output to a file.

manage.py dumpdata > file



来源:https://stackoverflow.com/questions/11546151/how-to-make-db-dumpfile-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!