开发者

Add Property to Django Result Object

I'm trying to add a property or two to a Django result object before I serialize it. I'm fairly weak in my Python skills, so here we go.

I want to do:

products = Product.objects.all()
products.totalP开发者_运维技巧ages = 10
products.currentPage = 1
data = serializers.serialize('json', products)

Without trying to add the totalPages and currentPage properties, this code works fine. But I'd like to add these properties so I can pass a nice looking JSON object back to the client.

Any thoughts?


Not sure where you would like those attrs to go onto that "list" that serialize returns. Maybe you would like the data to be in a key in the final result:

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)                                       

Maybe you can find use in aggregation and annotation: http://docs.djangoproject.com/en/dev/topics/db/aggregation/

Update: note that the behavior of the default serializer might not be what you want. The code in django.utils.simplejson.encoder is highly optimized but I'm not quite sure how you would make it use custom properties and such. In the past, I have just made a method/property on my model class that converts the data in the instance to a dict containing exactly what I want. So, instead of

data = json.loads(serializers.serialize('json', products))

you could use (provided you have defined a method, as_dict on Product):

data = [p.as_dict() for p in products]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜