本文介绍了自定义模型管理器方法和QuerySet方法之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力使自己成为撰写自定义经理的人.我发现在线文档很少.我玩弄代码,发现了以下模式:

I am trying to get my head around writing Custom managers. I found the online documentation a little sparse. Toying around myself with code, I discovered the following patterns:

给出以下模型...

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')
    ....

然后我得到以下结果...

I then get the following results...

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'

为什么通过数据库关系访问对象时调用Manager方法,而直接访问对象时调用Queryset方法呢?如果我想要一种可以普遍访问的方法(DRY),那么最好的解决方案是什么?

Why is it that the Manager methods are called when accessing the object through a DB relationship, but the Queryset methods are called when accessing the object directly? If I want the one method universally accessible (DRY), what would be the best solution?

推荐答案

看看 QuerySet.as_manager() 方法.它使您可以从查询集创建管理器,从而无需在自定义管理器和查询集中复制代码,

Have a look at the QuerySet.as_manager() method. It allows you to create a manager from a queryset, so that you don't need to duplicate code in a custom manager and queryset,

这篇关于自定义模型管理器方法和QuerySet方法之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 05:00