簡體   English   中英

尋找更好的OOP方法

[英]Looking for a better OOP approach

我想更新用戶余額。 當前要執行此操作,我必須保存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:這不是一個開放的問題,很明顯,我在嘗試做什么以及我在做什么。 謝謝 :)

Stalk的答案很好,但是當方法只做一件事和一件事時,我更喜歡它。 現在, .refresh()會處理兩件事。 計算余額和節省。 我將通過實現.refresh()方法來進一步分解它,但在視圖中這樣做。 (我也將其命名為refresh_balance而不是refresh,refresh意味着我們將刷新整個帳戶)。

account.refresh_balance()
account.save()

這使得.refresh_balance()的邏輯可以更改,但是.save()會被留下來做最好的事情。 將模型保存到數據庫。

這也將使您的代碼不易出現錯誤。 我們還將遵循“ The Zen of Python”(Python之禪)的用法:“顯式優於隱式”。

創建自定義模型方法很容易,例如refresh

class Account(models.Model):
    # ... some fields

    def refresh(self):
        # do needed stuff
        self.balance = self._balance()
        self.save()

然后調用它:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM