﻿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
32281	Prefetech Object - to_attr has ambiguous behavior when using a related lookup	Tal Perry	nobody	"**Code Example**
{{{
from django.db.models import Prefetch

p = Prefetch(""a_set"", to_attr=""my_a"")
assert p.prefetch_to == ""my_a""

p = Prefetch(""b__a_set"", to_attr=""my_a"")
assert p.prefetch_to == ""my_a"", p.prefetch_to

}}}

That last assertion fails because `p.prefetch_to == ""b__my_a""`

**Description and use case**
We have a models X, Y and Z
Z has a foreign key to Y and Y has a foreign key to Z 
We'd like to fetch X with all of it's Z's using prefetch related and to be able to set the attribute to ""z"" 

But as above, this doesn't seem to work. 

The [https://github.com/django/django/blob/bb64b99b78a579cb2f6178011a4cf9366e634438/django/db/models/query.py#L1570-L1587 relevant Django code] seems to ignore this use case (or discourage it?) and instead puts to ""z"" attribute on each ""Y"" 


{{{
            self.prefetch_to = LOOKUP_SEP.join(lookup.split(LOOKUP_SEP)[:-1] + [to_attr])

}}}



----

I assume ""fixing this"" is a breaking change, but could we do an explicit parameter for prefetch_to ?At the moment we're setting it manually after creating the prefetch object
"	New feature	closed	Database layer (models, ORM)	3.1	Normal	wontfix			Unreviewed	0	0	0	0	0	0
