Django prefetch_related on ManyToMany(through)

时间:2019-10-31 15:03:46

标签: python django django-models

我正在尝试减少对ManyToMany(through=)的查询数量,但似乎只是通过预取而导致n + 1。

型号:

class Member(ImmutableModel):
  organizations = models.ManyToManyField('Organizations', through='MemberOrg', related_name='members')

class MemberOrg(ImmutableModel):
  member = models.ForeignKey('Member', related_name='member_orgs')
  org = models.ForeignKey('Organization', related_name='member_orgs')

class Organization(ImmutableModel):

从干净的数据库中,如果我设置了以下模型:

member = Member.objects.create()
org = Organization.objects.create()
MemberOrg.objects.create(member=member, org=org)
MemberOrg.objects.create(member=member, org=org)

然后获取:

Member.objects.all().prefetch_related('member_orgs')

我得到以下查询:

(0.009) SELECT "main_member"."id", (...) FROM "main_member"; args=()
(0.010) SELECT "main_memberorg"."id", (...) FROM "main_memberorg" WHERE "main_memberorg"."member_id" IN (1); args=(1,)
(0.005) SELECT "main_member"."id", (...) FROM "main_member" WHERE "main_member"."id" = 1; args=(1,)
(0.003) SELECT "main_member"."id", (...) FROM "main_member" WHERE "main_member"."id" = 1; args=(1,)

我试图弄清楚为什么我每Member都会收到一个MemberOrg模型的查询。当我添加MemberOrg -s时,此行为继续。我在the docs中找不到任何提及,而these questions暗示这是他们解决问题的方式,但似乎并没有达到我的预期。

(注意:这只是一个示例架构-我的要求更加复杂,并且与该模型设置有关。)

Django:1.9.1
postgres:9.6

0 个答案:

没有答案