2014-09-29 71 views
-1

請幫忙避免重複的代碼。如何削減記錄?

我需要首先調用get_count_authors_entries()get_new_authors_entries的()

from django.db import models 
from django.contrib.auth.models import User, UserManager 


class UserProfile(User):    
    phone = models.CharField(
     max_length=50, 
     blank=False, 
    ) 
    skype = models.CharField(
     max_length=50, 
     blank=False, 
    ) 

    @classmethod 
    def get_new_authors_entries(self): 
     return self.objects.filter(is_active=1, is_superuser=0).order_by('-date_joined')  

    @classmethod 
    def get_count_authors_entries(self): 
     return self.objects.filter(is_active=1, is_superuser=0).order_by('-date_joined').count()   

回答

3

,不調用參數傳遞給一個類方法self。按照慣例,這用於實例:類方法的參數是cls

其次,方法之間的唯一區別是增加了count()。那麼,爲什麼你不能把這個結果與另一個結果聯繫起來呢?

@classmethod 
def get_count_authors_entries(cls): 
    return cls.get_new_authors_entries().count() 

另請注意,在Django中將這些方法放在自定義管理器中而不是使用類方法更爲習慣。最後,我會質疑爲什麼您需要count方法,因爲您可以將count()添加到get_new_authors_entries方法的結果中,無論您調用哪個方法。

0

當你可以逃脫一個時,沒有必要定義兩種方法。

@classmethod 
def get_authors_entries(cls): 
    return self.objects.filter(is_active=1, is_superuser=0).order_by('-date_joined') 

現在,如果你想獲得新的作者項就叫get_authors_entries,如果你想獲得數只需撥打該查詢集count方法返回。