Django 选择与反向外键相关的\u
我在Django有两个型号。第一个层次是什么工作职能(职位)向哪些其他职位报告,第二个层次是人员和他们拥有什么工作职能Django 选择与反向外键相关的\u,django,django-models,django-queryset,django-1.5,django-managers,Django,Django Models,Django Queryset,Django 1.5,Django Managers,我在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 = model
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
如果我使用查询集获取人员,我可以使用Person.objects加入(并避免第二次访问数据库)position并向报告对象。选择相关('position','position_ureports_to')。筛选(…)
,但有没有办法避免再次访问数据库以获取人员集?我尝试将“position\uu reports\u to\uu person\u set”
或只是将position\uu reports\u to\uu person
添加到select\u related
,但这似乎并没有改变查询。这就是与预取相关的的用途吗
我想创建一个自定义管理器,这样当我进行查询以获取人员记录时,我还可以获取他们的职位权限和他们的管理器的人员记录,而无需更多地往返于数据库。这就是我到目前为止所做的:
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(
)
是的,这就是prefetch\u related()
的用途。它需要额外的查询,但其目的是一次获取所有相关信息,而不是每个人一次
就你而言:
qs.select_related('position__report_to')
.prefetch_related('position__report_to__person_set')
应该需要两次查询,而不管原始查询集中的人数是多少
从以下方面比较此示例:
可能是打字错误,但应该是get\u queryset()
,而不是get\u query\u set
@Paolo在Django 1.5中是get\u query\u set
。
>>> Restaurant.objects.select_related('best_pizza')
.prefetch_related('best_pizza__toppings')