自定义模型管理器方法和 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'

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

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

最新更新