Skip to content

Commit

Permalink
Closes #3185: Improve performance for custom field access within temp…
Browse files Browse the repository at this point in the history
…lates
  • Loading branch information
jeremystretch committed May 29, 2019
1 parent 0804c1a commit 823257c
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 4 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
* [#3138](https://github.com/digitalocean/netbox/issues/3138) - Add 2.5GE and 5GE interface form factors
* [#3156](https://github.com/digitalocean/netbox/issues/3156) - Add site link to rack reservations overview
* [#3183](https://github.com/digitalocean/netbox/issues/3183) - Enable bulk deletion of sites
* [#3185](https://github.com/digitalocean/netbox/issues/3185) - Improve performance for custom field access within templates
* [#3186](https://github.com/digitalocean/netbox/issues/3186) - Add interface name filter for IP addresses

## Bug Fixes
Expand Down
12 changes: 8 additions & 4 deletions netbox/extras/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ def clean(self):
#

class CustomFieldModel(models.Model):
_cf = None

class Meta:
abstract = True
Expand All @@ -111,9 +112,12 @@ def cf(self):
"""
Name-based CustomFieldValue accessor for use in templates
"""
if not hasattr(self, 'get_custom_fields'):
return dict()
return {field.name: value for field, value in self.get_custom_fields().items()}
if self._cf is None:
# Cache all custom field values for this instance
self._cf = {
field.name: value for field, value in self.get_custom_fields().items()
}
return self._cf

def get_custom_fields(self):
"""
Expand All @@ -126,7 +130,7 @@ def get_custom_fields(self):

# If the object exists, populate its custom fields with values
if hasattr(self, 'pk'):
values = CustomFieldValue.objects.filter(obj_type=content_type, obj_id=self.pk).select_related('field')
values = self.custom_field_values.all()
values_dict = {cfv.field_id: cfv.value for cfv in values}
return OrderedDict([(field, values_dict.get(field.pk)) for field in fields])
else:
Expand Down

0 comments on commit 823257c

Please sign in to comment.