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.totalPages = 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:
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.encoderis 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 ofyou could use (provided you have defined a method,
as_dicton Product):