28👍
✅
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
20👍
An even better way is to use Django’s built-in stdout redirection for their command modules. See docs here.
If you want to manipulate the stream before sending it to a file, you can also pass it a StringIO buffer:
import os
from cStringIO import StringIO
from django.core import management
def create_fixture(app_name, filename):
buf = StringIO()
management.call_command('dumpdata', app_name, stdout=buf)
buf.seek(0)
with open(filename, 'w') as f:
f.write(buf.read())
- [Django]-Multiple applications with django
- [Django]-What is the deal with the pony in Python community?
- [Django]-Django Admin linking to related objects
3👍
I am using Django fixture magic https://github.com/davedash/django-fixture-magic and need to dump a custom fixture. I tried several ways but ended up using Amyth’s answer becuase it was the only way that worked.
Here is my admin action that works with fixture magic
def export_survey(modeladmin, request, queryset):
sysout = sys.stdout
survey = queryset[0]
fname = "%s.json" %(survey.slug)
response = HttpResponse(mimetype='application/json')
response['Content-Disposition'] = 'attachment; filename=%s' %(fname)
sys.stdout = response
call_command('custom_dump', 'complete_survey', survey.id)
sys.stdout = sysout
return response
export_survey.short_description = "Exports a single survey as a .json file"
- [Django]-Django default_from_email name
- [Django]-Setting up Django on AWS Elastic Beanstalk: WSGIPath not found
- [Django]-Django – How to increment integer field from user input?
3👍
DB fixtures typically compress well, and loaddata
can read compressed fixtures. To write a .bz2
compressed fixture directly:
import bz2
with bz2.BZ2File('db.json.bz2', 'w', buffering=1024) as f:
django.core.management.call_command('dumpdata', stdout=f)
- [Django]-Django: show a ManyToManyField in a template?
- [Django]-Django : Table doesn't exist
- [Django]-Django – How to sort queryset by number of character in a field
0👍
This one help for multiple dump data into json file
from django.core.management import call_command
import sys
sys.stdout = open('app_one/fixtures/apple.json', 'w')
call_command('dumpdata', 'app_one.apple')
sys.stdout = open('app_two/fixtures/banana.json', 'w')
call_command('dumpdata', 'app_two.banana')
- [Django]-Is Django admin difficult to customize?
- [Django]-Django filter events occurring today
- [Django]-How do I reuse HTML snippets in a django view
Source:stackexchange.com