在我的应用程序中,我试图将数据库数据保存到 JSON 文件中。
这是我的views.py:
if request.POST:
form = BookForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
form.save()
JSONSerializer = serializers.get_serializer("json")
json_serializer = JSONSerializer()
with open("book.json", "w") as out:
json_serializer.serialize(Book.objects.all(), stream=out)
return redirect('/index/')
return render_to_response('addbook.html',{ 'form':form },context_instance=RequestContext(request))
我正在使用序列化程序来做到这一点。
问题是数据保存在数据库中,但没有写入文件。
运行上述代码时出现以下错误
IOError at /addbook/
[Errno 2] No such file or directory: 'fixtures/book.json'
Request Method: POST
Request URL: http://localhost:8000/addbook/
Django Version: 1.3.7
Exception Type: IOError
Exception Value:
[Errno 2] No such file or directory: 'fixtures/book.json'
Exception Location: /root/Samples/DemoApp/DemoApp/views.py in addbook, line 53
Python Executable: /usr/bin/python
Python Version: 2.7.0