﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
26491	Duplicated queries with nested prefetch	Eduardo Klein	nobody	"This ticket may be related to #26318 , but it's not the same since it does not involve repeated models.

Consider the following 3 test models:
{{{
class Test1(models.Model):
    pass

class Test2(models.Model):
    test1 = models.ForeignKey(Test1, related_name=""tests2"")

class Test3(models.Model):
    test2 = models.ForeignKey(Test2, related_name=""tests3"")
}}}

Through the shell, we create initial entries and run the nested prefetch queries. We verify that the last 2 queries are duplicated:
{{{
from test.models import Test1, Test2, test3
from django.db import connection
from django.db.models import Prefetch

t1 = Test1.objects.create()
t2 = Test2.objects.create(test1 = t1)
t3 = Test3.objects.create(test2 = t2)

connection.queries_log.clear()

tests2_prefetch = Prefetch(""tests2"", Test2.objects.prefetch_related(""tests3""))
Test1.objects.prefetch_related(tests2_prefetch)

assert len(connection.queries) == 4
assert connection.queries[-1] == connection.queries[-2]
}}}

We had 4 queries instead of 3 expected and the last 2 are duplicated (to prefetch Test3 entries)."	Cleanup/optimization	closed	Database layer (models, ORM)	1.9	Normal	duplicate			Unreviewed	0	0	0	0	0	0
