【发布时间】:2013-05-07 09:42:04
【问题描述】:
我想更新用户余额。为此,目前我必须保存 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这不是一个悬而未决的问题,很清楚我正在尝试做什么以及我在追求什么。谢谢:)
【问题讨论】:
-
为什么不在 Account 模型中创建
refresh对象方法(不是静态的),它会执行所需的操作,然后从这个refresh方法调用self.save()? -
听起来像是你可以在数据库上使用存储过程来做的事情。
-
@Aya 存储过程会很好,但我现在正在代码中寻找一种方法,我不想在这个阶段将自己锁定在数据库中。
-
为什么不使用信号仅在创建交易时重新计算余额? (我假设事务只能创建 - 永远不会更新或删除,但即便如此你也可以使用信号)
-
@brunodesthuilliers:这可能行得通,但在添加许多事务时也会产生很多问题。我宁愿添加一个信号,仅在添加交易时清除余额,并在获取时计算它(如果清除)。但我没有那个代码。 :-)