2017-08-28 80 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()方法。它允许你从一个查询集创建一个管理器,这样你就不需要在一个自定义管理器和查询集中复制代码,

相关问题