【发布时间】: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