Opened 6 years ago

Closed 6 years ago

#28723 closed Bug (fixed)

RelatedManager.get_prefetch_queryset returns "wrong" cache_name

Reported by: Mike Hansen Owned by: nobody
Component: Database layer (models, ORM) Version: dev
Severity: Normal 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 (last modified by Mike Hansen)

Currently, RelatedManager.get_prefetch_queryset returns self.field.related_query_name() as the cache_name. In the case where no related_name has been set on the ForeignKey, then this does not match with the through_attr used by get_prefetcher.

Using the models in tests/prefetch_related/models.py,

BookWithYear.objects.prefetch_related('bookreview_set')

will use a through_attr of "bookreview_set", but "bookreview" is what will be placed in _prefetched_objects_cache.

I think related_manager.field.remote_field.get_accessor_name() should be used instead.

https://github.com/django/django/pull/9259 is a pull request which fixes this issue

Change History (9)

comment:1 by Mike Hansen, 6 years ago

Has patch: set

A pull request for this can be found at https://github.com/django/django/pull/9259

I wasn't sure on the best location for these tests so any guidance would be helpful.

comment:2 by Mike Hansen, 6 years ago

Description: modified (diff)

comment:3 by Mike Hansen, 6 years ago

Description: modified (diff)
Type: UncategorizedBug

comment:4 by Tim Graham, 6 years ago

Triage Stage: UnreviewedReady for checkin

comment:5 by Tim Graham <timograham@…>, 6 years ago

Resolution: fixed
Status: newclosed

In 514b2c98:

Fixed #28723 -- Fixed RelatedManager's prefetch_related() cache name.

comment:6 by Mike Hansen, 6 years ago

Thanks Tim!

comment:7 by Jon Dufresne, 6 years ago

Resolution: fixed
Status: closednew
Triage Stage: Ready for checkinAccepted

I believe this change is causing a regression as the _remove_prefetched_objects() method was not updated to use the new cache name. See line:

https://github.com/django/django/blob/514b2c989a948e3c59bda0da0c9427acf643cf5b/django/db/models/fields/related_descriptors.py#L578

I've created a PR to fix it.

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

In 8b218783:

Refs #28723 -- Fixed stale prefetch_related cache after add/remove.

Regression in 514b2c989a948e3c59bda0da0c9427acf643cf5b.

comment:9 by Tim Graham, 6 years ago

Resolution: fixed
Status: newclosed
Note: See TracTickets for help on using tickets.
Back to Top