﻿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
26373	Reverse lookup with subquery with a ForeignKey with to_field set causes django.core.exceptions.FieldError	Jason Parrott	nobody	"Reference pull request:
https://github.com/django/django/pull/6304

From 1.9, a model with a ForeignKey with a custom to_field set as below will error when used in a in subquery in a reverse relation context.

{{{
class Food(models.Model):
    name = models.CharField(max_length=20, unique=True)

class Eaten(models.Model):
    food = models.ForeignKey(Food, models.SET_NULL, to_field=""name"", null=True)
    meal = models.CharField(max_length=20)


apple = Food.objects.create(name=""apple"")
lunch = Eaten.objects.create(food=apple, meal=""lunch"")
self.assertEqual(
    set(Food.objects.filter(eaten__in=Eaten.objects.filter(meal='lunch'))),
    {apple}
)
}}}
{{{
django.core.exceptions.FieldError: Cannot resolve keyword 'name' into field. Choices are: food, food_id, id, meal
}}}

The reason is a recently added support for the non-reverse in lookup support in 1.9
{{{
foreign_fields = getattr(field, 'foreign_related_fields', ())
    if len(foreign_fields) == 1 and not foreign_fields[0].primary_key:
        return self.values(foreign_fields[0].name)
}}}
Depending on the base query's (self in the above case) model (self.model), foreign_related_fields's values are not correct. Or rather, they are only correct if the base model is not the same as the field's model.

This patch (in the PR) adds a simple if statement to check that.
As far as I can tell, if the reverse lookup situation, there was no need to have any special support."	Bug	closed	Database layer (models, ORM)	1.9	Release blocker	fixed			Accepted	1	0	0	0	0	0
