我有这个非常基本的问题,
>>> from django.core import serializers
>>> serializers.serialize("json", {'a':1})
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/lib/pymodules/python2.6/django/core/serializers/__init__.py", line 87, in serialize
s.serialize(queryset, **options)
File "/usr/lib/pymodules/python2.6/django/core/serializers/base.py", line 40, in serialize
for field in obj._meta.local_fields:
AttributeError: 'str' object has no attribute '_meta'
>>>
如何做到这一点?
答案 0 :(得分:14)
此外,由于您似乎使用的是Python 2.6,因此您可以直接使用json
模块:
import json
data = json.dumps({'a': 1})
答案 1 :(得分:6)
from django.utils import simplejson
data = simplejson.dumps({'a': 1})
答案 2 :(得分:0)
json
或simplejson
这样的库在序列化django对象时并不是很酷,当您可以在视图中使用django.core
中的序列化程序时:
from django.core import serializers
def json_for_model_instance(request, pk):
instance = YourModel.objects.get(pk=pk)
serialized_instance = serializers.serialize('json', [instance, ])
return HttpResponse(serialized_instance, content_type="application/json")