我想更新用户余额。要做到这一点目前我有救帐户对象,请考虑以下观点:寻找更好的面向对象方法
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