I want to update user balance. To do this, I currently need to save the Account object, consider the following view:
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)
In model.py, I have the following class methods that work on foot:
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
It looks cumbersome to me, I save again to save again (if that makes sense), and ideally I want to just call refresh () on any of my views whenever I want. I am not a Django expert and you need advice on how best to deal with this.
I looked at static methods , maybe?
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'?
Then just call Account.update_balance(Account) ?????
Any tips? PS This is not an open question; it is clear what I am trying to do and what I need. Thanks:)
source share