【问题标题】:What's the difference between Custom model manager methods and QuerySet methods?自定义模型管理器方法和 QuerySet 方法有什么区别?
【发布时间】:2017-08-28 12:38:14
【问题描述】:

我正在努力思考如何编写自定义管理器。我发现在线文档有点稀疏。玩弄自己的代码,我发现了以下模式:

鉴于以下模型...

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),最好的解决方案是什么?

【问题讨论】:

    标签: django django-models django-managers


    【解决方案1】:

    看看QuerySet.as_manager() 方法。它允许您从查询集中创建管理器,这样您就不需要在自定义管理器和查询集中重复代码,

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-03
      • 2019-06-17
      • 1970-01-01
      • 2017-12-11
      • 2011-08-02
      • 1970-01-01
      相关资源
      最近更新 更多