[Django]-Add Property to Django Result Object

6👍

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]

Leave a comment