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
The manage.py dumpdata command dumps the data from your database either in the command line or in a file that you specify. You do not want to it to dump everything, however, because it will make it difficult to load the data into another database. It created the file with the dumped data.
You can load data by calling manage.py loaddata <fixturename> , where <fixturename> is the name of the fixture file you've created. Each time you run loaddata , the data will be read from the fixture and reloaded into the database.
A data dump is the transfer of a large amount of data between two systems, often over a network connection. For example, a database can be dumped to another network server, where it could be utilized by other software applications or analyzed by a person.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With