1
0
mirror of https://github.com/netbox-community/netbox.git synced 2024-05-10 07:54:54 +00:00

Closes #15413: Enable caching of object attributes in search index

This commit is contained in:
Jeremy Stretch
2024-03-13 16:13:06 -04:00
parent 2d4295e2ed
commit 7357f953eb
2 changed files with 31 additions and 4 deletions

View File

@ -1,6 +1,9 @@
from collections import namedtuple from collections import namedtuple
from decimal import Decimal
from django.core.exceptions import FieldDoesNotExist
from django.db import models from django.db import models
from netaddr import IPAddress, IPNetwork
from ipam.fields import IPAddressField, IPNetworkField from ipam.fields import IPAddressField, IPNetworkField
from netbox.registry import registry from netbox.registry import registry
@ -56,6 +59,24 @@ class SearchIndex:
return FieldTypes.INTEGER return FieldTypes.INTEGER
return FieldTypes.STRING return FieldTypes.STRING
@staticmethod
def get_attr_type(instance, field_name):
"""
Return the data type of the specified object attribute.
"""
value = getattr(instance, field_name)
if type(value) is str:
return FieldTypes.STRING
if type(value) is int:
return FieldTypes.INTEGER
if type(value) in (float, Decimal):
return FieldTypes.FLOAT
if type(value) is IPNetwork:
return FieldTypes.CIDR
if type(value) is IPAddress:
return FieldTypes.INET
return FieldTypes.STRING
@staticmethod @staticmethod
def get_field_value(instance, field_name): def get_field_value(instance, field_name):
""" """
@ -82,7 +103,11 @@ class SearchIndex:
# Capture built-in fields # Capture built-in fields
for name, weight in cls.fields: for name, weight in cls.fields:
try:
type_ = cls.get_field_type(instance, name) type_ = cls.get_field_type(instance, name)
except FieldDoesNotExist:
# Not a concrete field; handle as an object attribute
type_ = cls.get_attr_type(instance, name)
value = cls.get_field_value(instance, name) value = cls.get_field_value(instance, name)
if type_ and value: if type_ and value:
values.append( values.append(

View File

@ -263,8 +263,10 @@ class SearchTable(tables.Table):
super().__init__(data, **kwargs) super().__init__(data, **kwargs)
def render_field(self, value, record): def render_field(self, value, record):
if hasattr(record.object, value): try:
return title(record.object._meta.get_field(value).verbose_name) model_field = record.object._meta.get_field(value)
return title(model_field.verbose_name)
except FieldDoesNotExist:
return value return value
def render_value(self, value): def render_value(self, value):