diff options
| author | François Freitag <mail@franek.fr> | 2017-03-03 18:45:31 -0800 |
|---|---|---|
| committer | Tim Graham <timograham@gmail.com> | 2017-05-04 09:55:35 -0400 |
| commit | c679ac04499798e366ca594f97e4f95d3da3682f (patch) | |
| tree | dfe16aeab068f20660f89f4e567ab6be232f7ac4 /django/db/models/query.py | |
| parent | fec151222ec3f492250662f1c8e84b5adc69603b (diff) | |
[1.11.x] Fixed #27554 -- Fixed prefetch_related() crash when fetching relations in nested Prefetches.
Backport of c0a2b9508aa2c6eaa22e9787010276edca887f0b from master
Diffstat (limited to 'django/db/models/query.py')
| -rw-r--r-- | django/db/models/query.py | 13 |
1 files changed, 9 insertions, 4 deletions
diff --git a/django/db/models/query.py b/django/db/models/query.py index 5069c419d1..c5e8b432fe 100644 --- a/django/db/models/query.py +++ b/django/db/models/query.py @@ -1471,10 +1471,15 @@ def prefetch_related_objects(model_instances, *related_lookups): # that we can continue with nullable or reverse relations. new_obj_list = [] for obj in obj_list: - try: - new_obj = getattr(obj, through_attr) - except exceptions.ObjectDoesNotExist: - continue + if through_attr in getattr(obj, '_prefetched_objects_cache', ()): + # If related objects have been prefetched, use the + # cache rather than the object's through_attr. + new_obj = list(obj._prefetched_objects_cache.get(through_attr)) + else: + try: + new_obj = getattr(obj, through_attr) + except exceptions.ObjectDoesNotExist: + continue if new_obj is None: continue # We special-case `list` rather than something more generic |
