Reputation: 6429
Given the below JSON result from tastypie, I would like to create a new value at check.payments_total which is equal to the total amount of the payments (in this case, 44.00). Any clue on how to do this? I'm completely stumped. payments is a joined foreign key to the check table.
{
"objects": [
{
"check": {
"id": "58a81b36-1ea6-403b-9902-a50cbd13cf2e",
"number": 2,
"payments": [
{
"amount": "5.00",
},
{
"amount": "39.00",
}
]
}
}
]
}
Upvotes: 0
Views: 223
Reputation: 9948
If for the response, then you could override the following method in your resource (the snippet is from tastypie.resources.Resource
):
def alter_list_data_to_serialize(self, request, data):
"""
A hook to alter list data just before it gets serialized & sent to the user.
Useful for restructuring/renaming aspects of the what's going to be
sent.
Should accommodate for a list of objects, generally also including
meta data.
"""
return data
just include something like (not tested, consider to be pseudo-code):
total_amount = 0.0
for object in data[ 'objects' ]:
total_amount += object[ 'amount' ]
return { 'objects' : data[ 'objects' ], 'total_amount' : total_amount }
and you should be done.
Upvotes: 1