使用python将数据库数据存储到json文件中

时间:2013-04-04 09:25:35

标签: python django json django-views

在我的应用程序中,我尝试将数据库数据保存到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

1 个答案:

答案 0 :(得分:1)

path = "{0}/app_name/fixtures/book.json".format(settings.PROJECT_ROOT)
with open(path, "w") as out:
    json_serializer.serialize(Book.objects.all(), stream=out)