Finding a Better OOP Approach

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:)

+4
source share
2 answers

The answer to the stem is good, but I prefer it when the methods do one and only one. As now, .refresh() has two functions. Calculation of balance and conservation. I would take it even further by implementing the .refresh() method, but in the view do it. (I would also call it refresh_balance instead of refresh, refresh means that we are updating the entire account).

 account.refresh_balance() account.save() 

This makes the logic for .refresh_balance() change, but .save() will be left alone to do what it does best. Save the model to the database.

It will also make your code less error prone. We will also follow The Zen of Python: "Explicit is better than implicit."

+4
source

It's easy to create your own model method, for example refresh :

 class Account(models.Model): # ... some fields def refresh(self): # do needed stuff self.balance = self._balance() self.save() 

And then just call it:

 # ... account = Account.objects.get(user=request.user) account.refresh() 
+2
source

Source: https://habr.com/ru/post/1479507/


All Articles