Django ORM使用prefetch_related来混淆相关对象

时间:2017-08-25 11:26:21

标签: django django-polymorphic

我遇到prefetch_related电话非常奇怪的行为。这是插图:

# First define two sketch models, just for convenience of the further talk.

class Secondary(models.Model):
    pass

class Primary(models.Model):
    secondaries = models.ManyToManyField(Secondary)

# Just to make clear, EVERY Primary object in my system has at least one
# related Secondary object.

# Now prepare a query.

primaries = Primary.objects.filter(...)\
                           .order_by(...)\
                           .prefetch_related('secondary')

# Iterating:

for primary in primaries:
    if not primary.secondaries.all():
        # So we have found an object that is said to not have
        # any relatives.  Re-query this particular object.
        # This part is hit in my code, although it should not.
        primary = Primary.objects.get(pk=primary.pk)
    for secondary in primary.secondaries.all():
        # Voila, there are relatives!
        # This part was not hit for some objects until I added
        # the re-query part above.
        pass

为了说清楚,我的系统中没有Primary个对象没有相关的Secondary个对象,但上面的代码仍然会触及其中一些对象的重新查询部分(总是相同的),并重新查询提取失踪的辅助。更奇怪的是,我可以看到一些Primaries在他们的secondaries.all()中重复了Secondaries - 整体印象是ORM错误地将一些Secondaries连接到错误的Primaries。

可能有什么不对?这是Django或数据库的一些错误吗?

我使用Django 1.10.5,psycopg2 2.7.3和Postgres 9.6。

更新:我发现问题更严重:有时ORM会返回相关对象的不完整列表,因此上面解释的解决方法无济于事。我们必须删除prefetch_related调用,因为显然我们不能依赖它返回的数据。

丹尼尔在评论中提到

更新2:,这里有一些真正的SQL查询(尽管不是我们遇到问题的系统)。 backend_build是“主要”模型,有几个“辅助”模型:backend_buildproblembackend_sanityproblembackend_runproblem - 我们使用django_polymorphic,基本模型是backend_problem

Python代码如下所示:

builds = Build.objects.filter(
    branch__active=True,
    type__active=True,
    finish_timestamp__gt=timezone.now() - timedelta(days=10))\
 .order_by('-finish_timestamp')\
 .prefetch_related('problems')

for build in builds:
  for problem in build.problems.all():
    print problem.id  # just a stub code to use results of the query.

以下是生成的SQL查询:

SELECT "backend_build"."teamcity_id", "backend_build"."status", "backend_build"."finish_timestamp", "backend_build"."type_id", "backend_build"."branch_id", "backend_build"."revision"
  FROM "backend_build"
  INNER JOIN "backend_buildtype" ON ("backend_build"."type_id" = "backend_buildtype"."id")
  INNER JOIN "backend_branch" ON ("backend_build"."branch_id" = "backend_branch"."id")
  WHERE ("backend_build"."finish_timestamp" > \'2017-08-18T06:35:21.322000+00:00\'::timestamptz AND "backend_buildtype"."active" = true AND "backend_branch"."active" = true)
  ORDER BY "backend_build"."finish_timestamp" DESC 

SELECT "backend_problem"."id", "backend_problem"."polymorphic_ctype_id", "backend_problem"."generic_type", "backend_problem"."startrack_id", "backend_problem"."useful", "backend_problem"."status", "backend_problem"."summary"
  FROM "backend_problem"
  INNER JOIN "backend_build_problems" ON ("backend_problem"."id" = "backend_build_problems"."problem_id")
  WHERE "backend_build_problems"."build_id" = 18984809

SELECT "backend_problem"."id", "backend_problem"."polymorphic_ctype_id", "backend_problem"."generic_type", "backend_problem"."startrack_id", "backend_problem"."useful", "backend_problem"."status", "backend_problem"."summary", "backend_sanityproblem"."problem_ptr_id", "backend_sanityproblem"."code", "backend_sanityproblem"."latest_occurred"
  FROM "backend_sanityproblem"
  INNER JOIN "backend_problem" ON ("backend_sanityproblem"."problem_ptr_id" = "backend_problem"."id")
  WHERE "backend_sanityproblem"."problem_ptr_id" IN (9251, 9252, 9253, 9254, 9255, 9256, 9257, 9259, 9261, 9262, 9263, 9264, 9268, 9269, 9270, 9271, 9272, 9273, 9274, 9275, 9276, 9277, 9280, 9283, 9285, 9287, 9290, 9293, 9294, 9295, 9297, 9302, 9303, 9304, 9306, 9307, 9309, 9312, 9313, 9314, 9316, 9317, 9319, 9321, 9322, 9062, 9063, 9066, 9068, 9092, 9107, 9109, 9112, 9648, 9649, 9650, 9651, 9652, 9653, 9654, 9655, 9656, 9657, 9658, 9659, 9660, 9661, 9662, 9663, 9664, 9665, 9666, 9667, 9668, 9669, 9670, 9671, 9672, 9673, 9674, 9675, 9676, 9677, 9678, 9679, 9680, 9681, 9682, 9683, 9684, 9685, 9686, 9687, 9688, 9689, 9690, 9691, 9692, 9693, 9694)

SELECT "backend_problem"."id", "backend_problem"."polymorphic_ctype_id", "backend_problem"."generic_type", "backend_problem"."startrack_id", "backend_problem"."useful", "backend_problem"."status", "backend_problem"."summary", "backend_sanityproblem"."problem_ptr_id", "backend_sanityproblem"."code", "backend_sanityproblem"."latest_occurred"
  FROM "backend_sanityproblem"
  INNER JOIN "backend_problem" ON ("backend_sanityproblem"."problem_ptr_id" = "backend_problem"."id")
  WHERE "backend_sanityproblem"."problem_ptr_id" IN (9344, 9345, 9488, 9489, 9508, 9509, 9510, 9511, 9512, 9513, 9399, 9401, 9402, 9403, 9426, 9436, 9572, 9573, 9574, 9575, 9330, 9337, 9338, 9339, 9340, 9341, 9342)

SELECT "backend_problem"."id", "backend_problem"."polymorphic_ctype_id", "backend_problem"."generic_type", "backend_problem"."startrack_id", "backend_problem"."useful", "backend_problem"."status", "backend_problem"."summary"
  FROM "backend_problem"
  INNER JOIN "backend_build_problems" ON ("backend_problem"."id" = "backend_build_problems"."problem_id")
  WHERE "backend_build_problems"."build_id" = 18944441

SELECT "backend_problem"."id", "backend_problem"."polymorphic_ctype_id", "backend_problem"."generic_type", "backend_problem"."startrack_id", "backend_problem"."useful", "backend_problem"."status", "backend_problem"."summary", "backend_buildproblem"."problem_ptr_id", "backend_buildproblem"."stage"
  FROM "backend_buildproblem"
  INNER JOIN "backend_problem" ON ("backend_buildproblem"."problem_ptr_id" = "backend_problem"."id")
  WHERE "backend_buildproblem"."problem_ptr_id" IN (9600)

SELECT "backend_problem"."id", "backend_problem"."polymorphic_ctype_id", "backend_problem"."generic_type", "backend_problem"."startrack_id", "backend_problem"."useful", "backend_problem"."status", "backend_problem"."summary"
  FROM "backend_problem"
  INNER JOIN "backend_build_problems" ON ("backend_problem"."id" = "backend_build_problems"."problem_id")
  WHERE "backend_build_problems"."build_id" = 18944330

还有更多这样的查询,我在这里省略了它们。从上面可以清楚地看出系统ritst查询主模型,然后请求每个主要对象的关系,并考虑它们的多态类型。

1 个答案:

答案 0 :(得分:1)

我怀疑您的问题源于您有多个具有相同基本模型的辅助模型的事实。可能有一个内部缓存被每个查询覆盖。尝试将prefetch_related语句限制为problems模型:

.prefetch_related('problems')

或者它可能与this issue with django-polymorphic有关?