我想更新用戶餘額。要做到這一點目前我有救帳戶對象,請考慮以下觀點:尋找更好的面向對象方法
def refresh_balance(request):
"""
Balance Refresh.
The balance shown on every page is a cached balance for performance reasons.
To get the real balance you need to re-save the account object which will refresh
the cached value in the database.
"""
page = request.GET['redirect']
account = Account.objects.get(user=request.user)
account.save()
message_user(
request.user,
"Account Balance Refreshed.")
return HttpResponseRedirect(page)
在model.py我有以下類方法,做腿部的工作:
def save(self, *args, **kwargs):
self.balance = self._balance()
return super(Account, self).save(*args, **kwargs)
def _balance(self):
aggregates = self.transactions.aggregate(sum=Sum('amount'))
sum = aggregates['sum']
return D('0.00') if sum is None else sum
這對我來說看起來很麻煩,我重新保存以重新保存(如果這是有道理的),並且理想情況下我只想在任何我的視圖中調用refresh(),只要我想要。我不是Django專家,需要一些關於如何更好地處理這個問題的建議。
我看過靜態方法也許?
def _balance(self):
aggregates = self.transactions.aggregate(sum=Sum('amount'))
sum = aggregates['sum']
return D('0.00') if sum is None else sum
@staticmethod
def update_balance(model):
model.balance = unsure here as I need 'self'?
然後只調用Account.update_balance(Account)
?????
有什麼建議嗎? PS這不是一個懸而未決的問題,它很清楚我想要做什麼以及之後的事情。謝謝:)
爲什麼不在Account模型中創建'refresh'對象方法(不是靜態的),它會執行所需的操作,然後從這個'refresh'方法調用'self.save()'? – stalk 2013-05-07 09:53:55
聽起來就像你可以用數據庫上的存儲過程做的事情。 – Aya 2013-05-07 09:57:38
@Aya商店程序會很好,但我正在代碼中尋找一種方法,並且我不想在這個階段將自己鎖定在數據庫中。 – GrantU 2013-05-07 10:07:58