2013-04-18 8 views
9

call_command 메서드를 사용하여 dumpdata를 호출하려고합니다. command. 수동으로 다음과 같이 사용하여 데이터를 파일에 저장합니다.call_command를 dumpdata 명령과 함께 사용하여 json을 파일에 저장하는 방법

python manage.py dumpdata appname_one appname_two > /path/to/save/file.json 

그것은 JSON 파일을 저장합니다. 이제는 call_command 메서드를 사용하여이 명령을 호출해야하는 상황에 처해 있습니다. 나는 다음과 같은 사용하여 명령에서 JSON을 인쇄 할 수 있어요

:

from django.core.management import call_command 

call_command('dumpdata', 'appname_one', 'appname_two') 

우리가 명령 줄에서처럼 내가 파일에 주어진 데이터를 저장할 수있는 방법이 있나요?

답변

11

은 위의 내용을 달성하기 위해 sys.stdout을 파일로 리디렉션해야했습니다. 뭔가.

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 
+1

감사 Amyth : 직접 .bz2 압축 고정을 작성합니다. 이것은 django-fixture-magic을 사용하여 admin 액션에서 custom_dump를 할 때 사용해야했던 것입니다. – wilblack

10

더 좋은 방법은 자신의 명령 모듈에 대한 장고에 내장 된 표준 출력 리디렉션을 사용하는 것입니다. docs here을 참조하십시오.

파일로 전송하기 전에 스트림을 조작하려는 경우, 당신은 또한 그것을있는 StringIO 버퍼를 전달할 수 있습니다 내가 https://github.com/davedash/django-fixture-magic 마법 장고기구를 사용하여 사용자 정의 고정 덤프 필요하고

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

'create_fixture'는 다음과 같이 단순화 될 수 있다고 생각합니다 : open (filename, 'w') with f : management.call_command ('dumpdata', app_name, stdout = f) –

2

. 몇 가지 방법을 시도했지만 그것이 효과가있는 유일한 방법 이었기 때문에 Amyth의 대답을 사용하는 것으로 끝 맺었습니다.

여기에 마법기구와 함께 작동 내 관리 조치

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" 
0

DB기구는 일반적으로 잘 압축하고, loaddata 압축 설비를 읽을 수있다.

import bz2 

with bz2.BZ2File('db.json.bz2', 'w', buffering=1024) as f: 
    django.core.management.call_command('dumpdata', stdout=f)