不知道,你想那些ATTRS去到該序列返回該「清單」。也許你希望數據是在最終結果的關鍵:
import json
from django.core import serializers
products = Product.objects.all()
# data is a python list
data = json.loads(serializers.serialize('json', products))
# d is a dict
d = {}
# data is a list nested in d
d['results'] = data
# more keys for d
d['totalPages'] = 10
d['currentPage'] = 1
# data is a json string representation of the dict
data = json.dumps(d)
也許你可以找到在聚集和註釋使用:http://docs.djangoproject.com/en/dev/topics/db/aggregation/
更新:請注意,默認的序列的行爲可能不成爲你想成爲的人。 django.utils.simplejson.encoder
中的代碼是高度優化的,但我不太確定如何使其使用自定義屬性等。在過去,我剛剛在模型類上創建了一個方法/屬性,將實例中的數據轉換爲包含我想要的字典。所以,與其
data = json.loads(serializers.serialize('json', products))
您可以使用(前提是你已經定義了一個方法,as_dict
產品):
data = [p.as_dict() for p in products]
'數據= serializers.serialize( 'JSON',產品)'返回「列表「...所以不知道你想要這些額外的屬性去。 – 2011-03-01 04:25:46