import simplejson as json
results = Content.objects.filter(blah)
theresult_json = json.dumps(results)
這是行不通的!如何快速將查詢結果集轉儲到JSON中?
import simplejson as json
results = Content.objects.filter(blah)
theresult_json = json.dumps(results)
這是行不通的!如何快速將查詢結果集轉儲到JSON中?
如何http://docs.djangoproject.com/en/dev/topics/serialization/
?
from django.core import serializers
data = serializers.serialize('json', SomeModel.objects.all())
# it's pretty useful and quick.
data = serializers.serialize('json', SomeModel.objects.all(), fields=('foo','bar'))
根據您要做的事情,您可能還想查看Piston。它具有特殊的Emitter類,用於將對象轉儲爲JSON格式,XML格式等。如果您正在構建AJAX或API端點,則活塞框架非常有用。
results
是一個python對象。 simplejson.dumps
只適用於python字典/列表。
您需要先將結果對象轉換爲字典。要麼你做手工是這樣的:
l = []
for result in results:
d = {
'attr1': result.attr1,
'attr2': result.attr2,
...
}
l.append(d)
theresult_json = simplejson.dumps(l)
或動態與對象__dict__
方法,從中除去未JSON序列化的屬性算賬:
l = []
for result in results:
d = result.__dict__
# remove attributes from dict which are not JSON-serializable with del d[key]
l.append(d)
theresult_json = simplejson.dumps(l)