'How to make db dumpfile in django
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
Solution 1:[1]
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).
Solution 2:[2]
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
Solution 3:[3]
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
Solution 4:[4]
According to recent documentation (Django 4.0), you can do
./manage.py dumpdata -o output_file.json
And you can even compress it with .gz for example:
./manage.py dumpdata -o output_file.json.gz
Solution 5:[5]
You can dump all database models data by using below code
from django.core.management import call_command
with open("data.json", "w", encoding="utf-8") as fp:
call_command("dumpdata", format="json", indent=2, stdout=fp)
This will create a file (data.json) in the root of your project folder.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tadeck |
| Solution 2 | Evhz |
| Solution 3 | dani herrera |
| Solution 4 | AC Souza |
| Solution 5 | ozcanyarimdunya |
