我想更新用户余额。为此,目前我必须保存Account对象,请考虑以下视图:
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这不是一个悬而未决的问题,很清楚我正在尝试做什么以及我在追求什么。谢谢 :)