#26373 closed Bug (fixed)
Reverse lookup with subquery with a ForeignKey with to_field set causes django.core.exceptions.FieldError
| Reported by: | Jason Parrott | Owned by: | nobody |
|---|---|---|---|
| Component: | Database layer (models, ORM) | Version: | 1.9 |
| Severity: | Release blocker | Keywords: | |
| Cc: | Triage Stage: | Accepted | |
| Has patch: | yes | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | no |
| Easy pickings: | no | UI/UX: | no |
Description
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.
Change History (4)
comment:1 by , 10 years ago
| Patch needs improvement: | set |
|---|---|
| Severity: | Normal → Release blocker |
| Triage Stage: | Unreviewed → Accepted |
| Type: | Uncategorized → Bug |
comment:2 by , 10 years ago
| Patch needs improvement: | unset |
|---|
The current PR has a test failure on PostgreSQL. You may also add a release note in
docs/releases/1.9.5.txt. Please uncheck "patch needs improvement" when the PR is updated. Thanks!