Opened 8 years ago

Closed 8 years ago

Last modified 8 years ago

#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 Tim Graham, 8 years ago

Patch needs improvement: set
Severity: NormalRelease blocker
Triage Stage: UnreviewedAccepted
Type: UncategorizedBug

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!

comment:2 by Jason Parrott, 8 years ago

Patch needs improvement: unset

comment:3 by Tim Graham <timograham@…>, 8 years ago

Resolution: fixed
Status: newclosed

In 4c1c930:

Fixed #26373 -- Fixed reverse lookup crash with a ForeignKey to_field in a subquery.

comment:4 by Tim Graham <timograham@…>, 8 years ago

In 4e8c265:

[1.9.x] Fixed #26373 -- Fixed reverse lookup crash with a ForeignKey to_field in a subquery.

Backport of 4c1c93032f4a015cbb4b33958603d18ac43515b4 from master

Note: See TracTickets for help on using tickets.
Back to Top