2012-09-11 137 views
0

鑑於tastypie下面的JSON結果,我想在check.payments_total上創建一個新值,該值等於付款總額(在本例中爲44.00)。有關如何做到這一點的任何線索?我完全被難住了。支付是檢查表的連接外鍵。django tastypie獲取相關列的總金額

{ 
"objects": [ 
    { 
     "check": { 
      "id": "58a81b36-1ea6-403b-9902-a50cbd13cf2e", 
      "number": 2, 
      "payments": [ 
       { 
        "amount": "5.00", 
       }, 
       { 
        "amount": "39.00", 
       } 
      ] 
     } 
    } 
] 
} 
+0

您是否希望在回覆中付款或在數據庫中支付所有款項? – kgr

+0

我猜想:對於響應 – Anentropic

+0

是的,只是爲了迴應 –

回答

1

如果響應,那麼你可以在你的資源覆蓋以下方法(片段是從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 

只包括像(未測試,認爲是僞代碼):

total_amount = 0.0 
for object in data[ 'objects' ]: 
    total_amount += object[ 'amount' ] 

return { 'objects' : data[ 'objects' ], 'total_amount' : total_amount } 

你應該完成。

+0

非常感謝這些信息。我會盡量實現這一點,並讓你知道它是如何發生的。 –

+0

聽起來不錯。祝你好運 ! :) – kgr

+0

謝謝,邏輯工作很好。 –