我已经在我的观点中做到了:
要序列化数据,我已经完成:
@login_required
@product_1_activation
def getcompanyObject(request, pk):
company_details = get_object_or_404(company, pk=pk)
all_objects = list(Company.objects.filter(pk=pk)) + list(Group1.objects.filter(Company=company_details.pk)) + list(Ledger1.objects.filter(Company=company_details.pk)) + list(Journal.objects.filter(Company=company_details.pk)) +
data = serializers.serialize('json', all_objects)
data = json.dumps(json.loads(data), indent=4)
response = HttpResponse(data , content_type='application/json')
response['Content-Disposition'] = 'attachment; filename={}-{}.json'.format(company_details.Name,datetime.now())
return response
然后我尝试:
from django.core.management import call_command
@login_required
def company_upload(request):
if request.method == 'POST':
new_company = request.FILES['myfile']
obj_generator = serializers.json.Deserializer(new_company)
for obj in obj_generator:
call_command('loaddata', obj, verbosity=0)
return render(request, 'company/import.html')
类似于python manage.py loaddata
。
但是当我尝试执行此操作时,出现以下错误:
Problem installing fixture '<DeserializedObject: company': company(pk=87)> is not a known serialization format.
谁能告诉我为什么会这样?如果我的代码有任何错误,请帮助我纠正错误。
谢谢
答案 0 :(得分:0)
您可能需要先将文件保存到磁盘。 loaddata
命令期望参数为磁盘上fixture file的路径。
您可以将上传的文件保存到临时文件,然后在其上调用loaddata
。
例如:
import tempfile
from django.core.management import call_command
@login_required
@product_1_activation
def company_upload(request):
if request.method == 'POST':
new_company = request.FILES['myfile']
with tempfile.NamedTemporaryFile(dir='/tmp') as temp:
for chunk in new_company.chunks():
temp.write(chunk)
call_command('loaddata', '/tmp/{}'.format(temp.name), verbosity=0)
return render(request, 'company/import.html')