简体   繁体   English

寻找更好的OOP方法

[英]Looking for a better OOP approach

I want to update a users balance. 我想更新用户余额。 To do this currently I have to save the Account object, consider the following view: 当前要执行此操作,我必须保存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)

In the model.py I have the following Class Methods that does the leg work: 在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

This to me look cumbersome, I'm re-saving to re-save (if that makes sense) and ideally I want to just call refresh() within any of my views, whenever I want. 在我看来,这很麻烦,我节省了重新保存(如果有意义)的操作,并且理想情况下,我想随时随地在我的任何视图中调用refresh()。 I'm no Django expert and need some advice on how to better handle this. 我不是Django专家,因此需要一些有关如何更好地处理此问题的建议。

I have 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 calling Account.update_balance(Account) ????? 然后只需调用Account.update_balance(Account) ?????

Any advice? 有什么建议吗? PS this is not an open question, it's clear what I'm trying to do and what I'm after. PS:这不是一个开放的问题,很明显,我在尝试做什么以及我在做什么。 Thanks :) 谢谢 :)

Stalk's answer is good but I prefer it when methods do one thing and one thing only. Stalk的答案很好,但是当方法只做一件事和一件事时,我更喜欢它。 As it is now, .refresh() takes care of two things. 现在, .refresh()会处理两件事。 Computing balance and saving. 计算余额和节省。 I would break it up even further by implementing the .refresh() method but in the view do this. 我将通过实现.refresh()方法来进一步分解它,但在视图中这样做。 (Also I would name it refresh_balance instead of refresh, refresh implies that we refresh the whole account). (我也将其命名为refresh_balance而不是refresh,refresh意味着我们将刷新整个帐户)。

account.refresh_balance()
account.save()

This makes it so that the logic for .refresh_balance() can change but the .save() would be left alone to do what it makes best. 这使得.refresh_balance()的逻辑可以更改,但是.save()会被留下来做最好的事情。 Save your model to the database. 将模型保存到数据库。

This will also make your code less prone to bugs. 这也将使您的代码不易出现错误。 We'll also follow The Zen of Python by: "explicit is better than implicit". 我们还将遵循“ The Zen of Python”(Python之禅)的用法:“显式优于隐式”。

It is easy to create custom model method, for example refresh : 创建自定义模型方法很容易,例如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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM