[1.8.x] Refs #25693 -- Avoided redundant calls to get_fields() in `to_attr` validation.

Backport of 4a9c32f5ee from master
This commit is contained in:
Simon Charette 2015-11-11 00:40:20 -05:00
parent 74a5664461
commit a3baee2f62
1 changed files with 14 additions and 11 deletions

View File

@ -1631,20 +1631,23 @@ def prefetch_one_level(instances, prefetcher, lookup, level):
rel_attr_val = rel_obj_attr(rel_obj) rel_attr_val = rel_obj_attr(rel_obj)
rel_obj_cache.setdefault(rel_attr_val, []).append(rel_obj) rel_obj_cache.setdefault(rel_attr_val, []).append(rel_obj)
for obj in instances:
instance_attr_val = instance_attr(obj)
vals = rel_obj_cache.get(instance_attr_val, [])
to_attr, as_attr = lookup.get_current_to_attr(level) to_attr, as_attr = lookup.get_current_to_attr(level)
# Make sure `to_attr` does not conflict with a field.
# Check we are not shadowing a field on obj. if as_attr and instances:
if as_attr: # We assume that objects retrieved are homogeneous (which is the premise
# of prefetch_related), so what applies to first object applies to all.
model = instances[0].__class__
try: try:
field = obj._meta.get_field(to_attr) model._meta.get_field(to_attr)
except exceptions.FieldDoesNotExist: except exceptions.FieldDoesNotExist:
pass pass
else: else:
msg = 'to_attr={} conflicts with a field on the {} model.' msg = 'to_attr={} conflicts with a field on the {} model.'
raise ValueError(msg.format(to_attr, field.model.__name__)) raise ValueError(msg.format(to_attr, model.__name__))
for obj in instances:
instance_attr_val = instance_attr(obj)
vals = rel_obj_cache.get(instance_attr_val, [])
if single: if single:
val = vals[0] if vals else None val = vals[0] if vals else None