我在Django 有两个模特.第一个层次是什么工作职能(职位)向哪些其他职位汇报,第二个层次是人员及其担任的工作职能.
class PositionHierarchy(model.Model):
pcn = models.CharField(max_length=50)
title = models.CharField(max_length=100)
level = models.CharField(max_length=25)
report_to = models.ForeignKey('PositionHierachy', null=True)
class Person(model.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
...
position = models.ForeignKey(PositionHierarchy)
当我有个人记录,并且我想找到该人的经理时,我必须这样做
manager = person.position.report_to.person_set.all()[0]
# Can't use .first() because we haven't upgraded to 1.6 yet
如果我得到的是QuerySet
分的人,我可以加入position并向using Person.objects.select_related('position', 'position__reports_to').filter(...)
报告(并避免第二次访问数据库),但是有没有办法避免再次访问数据库以获得person设置?我试着在select_related
中添加'position__reports_to__person_set'
或position__reports_to__person
,但这似乎并没有改变查询.这就是prefetch_related
的用途吗?
我想创建一个自定义管理器,这样当我进行查询以获取人员记录时,我还可以获得他们的PositionHeirarchy和他们经理的人员记录,而不需要往返于数据库.这就是我到目前为止所掌握的情况:
class PersonWithManagerManager(models.Manager):
def get_query_set(self):
qs = super(PersonWithManagerManager, self).get_query_set()
return qs.select_related(
'position',
'position__reports_to',
).prefetch_related(
)