#26373: Reverse lookup with subquery with a ForeignKey with to_field set causes
django.core.exceptions.FieldError
----------------------------------------------+--------------------
Reporter: Moncader | Owner: nobody
Type: Uncategorized | Status: new
Component: Database layer (models, ORM) | Version: 1.9
Severity: Normal | Keywords:
Triage Stage: Unreviewed | Has patch: 1
Easy pickings: 0 | UI/UX: 0
----------------------------------------------+--------------------
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.
--
Ticket URL: <https://code.djangoproject.com/ticket/26373>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-updates/051.0ded552acaddd69b645022546ed8de76%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.