2017-08-28 126 views
1

我試圖讓我的頭在編寫自定義管理器。我發現在線文檔有點稀疏。我身邊玩弄的代碼,我發現了以下模式:自定義模型管理器方法和QuerySet方法有什麼區別?

考慮下面的模型......

class QuestionQuerySet(models.QuerySet): 
    def QS_first (self): 
     return self.first() 

class QuestionManager(models.Manager): 
    def get_queryset(self): 
     return QuestionQuerySet(self.model, using=self._db) 

    def MN_first(self): 
     return self.get_queryset().first() 


class Question(models.Model): 
    front = models.ForeignKey('Sentence', related_name='question_fronts') 
    .... 

然後我得到下面的結果...

Grammar.objects.filter(stage=1).question_set.MN_first() 
<Question: [<Sentence: eve gideceğim>, <Sentence: I will go home>]> 

Grammar.objects.filter(stage=1).question_set.QS_first() 
AttributeError: 'RelatedManager' object has no attribute 'QS_first' 

Question.objects.filter(grammar=1).QS_first() 
<Question: [<Sentence: eve gideceğim>, <Sentence: I will go home>]> 

Question.objects.filter(grammar=1).MN_first() 
AttributeError: 'QuestionQuerySet' object has no attribute 'MN_first' 

爲什麼在通過DB關係訪問對象時調用Manager方法但是直接訪問對象時會調用Queryset方法?如果我想要一種通用的方法(DRY),那麼最好的解決方案是什麼?

回答

1

看看QuerySet.as_manager()方法。它允許你從一個查詢集創建一個管理器,這樣你就不需要在一個自定義管理器和查詢集中複製代碼,

相關問題