我正试着去编写自定义管理器。我发现在线文档有点稀疏。用代码玩弄自己,我发现了以下模式:
鉴于以下模型......
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'
为什么在通过数据库关系访问对象时调用Manager方法,但在直接访问对象时调用Queryset方法?如果我想要一种普遍可访问的方法(DRY),那么最佳解决方案是什么?