Просмотр исходного кода

Closes #23875: Serialize template object fields lazily

Restricted rendering serialized the full REST API representation of
every object up front, however few fields a template read, and
loaded related objects one at a time. Each field is now serialized
for a whole batch of objects when a template first reads it. Reverse
relations and lazily related objects are loaded per batch as well.
The values a template receives are unchanged.
Jeremy Stretch 8 часов назад
Родитель
Сommit
cd16a9ce2d

+ 32 - 26
netbox/extras/api/customfields.py

@@ -65,6 +65,37 @@ class CustomFieldsDataField(Field):
             )
         return self._nested_serializers[(serializer_class, many)]
 
+    def get_object_cache(self, instances):
+        """
+        Return the targets of object and multi-object custom fields set on the given objects, keyed by (model, pk).
+        """
+        object_type_cfs = [
+            cf for cf in self._get_custom_fields()
+            if cf.type in (CustomFieldTypeChoices.TYPE_OBJECT, CustomFieldTypeChoices.TYPE_MULTIOBJECT)
+        ]
+        pks_by_model = {}
+        for cf in object_type_cfs:
+            pks = pks_by_model.setdefault(cf.related_object_type.model_class(), set())
+            for item in instances:
+                raw = item.custom_field_data.get(cf.name)
+                if raw is not None:
+                    if cf.type == CustomFieldTypeChoices.TYPE_MULTIOBJECT:
+                        pks.update(raw)
+                    else:
+                        pks.add(raw)
+        cache = {}
+        for model, pks in pks_by_model.items():
+            objects = list(model.objects.filter(pk__in=pks))
+            # A target model may lack a REST serializer, so plan only for found targets
+            if objects:
+                serializer_class = get_serializer_for_model(model)
+                # Targets render with their nested (brief) representation
+                fields = getattr(serializer_class.Meta, 'brief_fields', None)
+                prefetch_related_objects(objects, *get_prefetches_for_serializer(serializer_class, fields=fields))
+            for obj in objects:
+                cache[(model, obj.pk)] = obj
+        return cache
+
     def to_representation(self, obj):
         data = {}
         cache = self.parent.context.get('cf_object_cache')
@@ -151,30 +182,5 @@ class CustomFieldListSerializer(ListSerializer):
     def to_representation(self, data):
         cf_field = self.child.fields.get('custom_fields')
         if isinstance(cf_field, CustomFieldsDataField):
-            object_type_cfs = [
-                cf for cf in cf_field._get_custom_fields()
-                if cf.type in (CustomFieldTypeChoices.TYPE_OBJECT, CustomFieldTypeChoices.TYPE_MULTIOBJECT)
-            ]
-            pks_by_model = {}
-            for cf in object_type_cfs:
-                pks = pks_by_model.setdefault(cf.related_object_type.model_class(), set())
-                for item in data:
-                    raw = item.custom_field_data.get(cf.name)
-                    if raw is not None:
-                        if cf.type == CustomFieldTypeChoices.TYPE_MULTIOBJECT:
-                            pks.update(raw)
-                        else:
-                            pks.add(raw)
-            cache = {}
-            for model, pks in pks_by_model.items():
-                objects = list(model.objects.filter(pk__in=pks))
-                # A target model may lack a REST serializer, so plan only for found targets
-                if objects:
-                    serializer_class = get_serializer_for_model(model)
-                    # Targets render with their nested (brief) representation
-                    fields = getattr(serializer_class.Meta, 'brief_fields', None)
-                    prefetch_related_objects(objects, *get_prefetches_for_serializer(serializer_class, fields=fields))
-                for obj in objects:
-                    cache[(model, obj.pk)] = obj
-            self.child.context['cf_object_cache'] = cache
+            self.child.context['cf_object_cache'] = cf_field.get_object_cache(data)
         return super().to_representation(data)

+ 1 - 1
netbox/extras/views.py

@@ -1314,7 +1314,7 @@ class ObjectRenderConfigView(generic.ObjectView):
             try:
                 render_context, state = config_template.prepare_render(context=context_data, user=request.user)
                 if state is not None:
-                    # Show the restricted context, as the template receives it (before it fetches anything)
+                    # Show the restricted context, as the template receives it
                     context_data = get_template_context_data(render_context)
                 rendered_config = config_template.render_prepared(render_context, state)
             except Exception as e:

+ 2 - 1
netbox/utilities/jinja2.py

@@ -175,12 +175,13 @@ class RestrictedSandboxedEnvironment(SandboxedEnvironment):
 class RestrictedRenderState:
     """
     State shared across a single restricted render: the user on whose behalf it runs, the maximum number of objects
-    query() may return (if any), and a cache of fetched objects.
+    query() may return (if any), a cache of fetched objects, and the serializers which represent them.
     """
     def __init__(self, user=None, max_results=None):
         self.user = user
         self.max_results = max_results
         self.cache = {}
+        self.serializers = {}
 
 
 #

+ 373 - 119
netbox/utilities/template_objects.py

@@ -10,9 +10,13 @@ from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelatio
 from django.contrib.contenttypes.models import ContentType
 from django.core.exceptions import FieldDoesNotExist
 from django.db import models
+from django.db.models import prefetch_related_objects
 from django.utils.datastructures import MultiValueDict
 from jinja2.exceptions import TemplateRuntimeError
 from netaddr import IPAddress, IPNetwork
+from rest_framework.fields import SkipField
+from rest_framework.relations import PKOnlyObject
+from rest_framework.serializers import Serializer
 
 from netbox.api.exceptions import SerializerNotFound
 from netbox.api.fields import RelatedObjectsField
@@ -58,6 +62,9 @@ _relations = {}
 # Marks a field holding generic object references ({object_type, object_id, object}), e.g. cable terminations
 _GENERIC_OBJECTS = object()
 
+# Marks a field for which an object has no value (e.g. an object the rendering user may not view)
+_MISSING = object()
+
 
 def get_template_object(instance, state):
     """
@@ -66,13 +73,11 @@ def get_template_object(instance, state):
     """
     _check_state(state)
     model = type(instance)
-    if (serializer_class := _get_serializer_class(model)) is None:
+    if _get_serializer_class(model) is None:
         raise ValueError(f"{model._meta.label} has no REST API serializer.")
-    # Reload the object from the REST API viewset's queryset, which may annotate fields the serializer renders
-    queryset = _prepare_queryset(_get_base_queryset(model).filter(pk=instance.pk), serializer_class)
-    data = _serialize(serializer_class, queryset.first() or instance)
-    state.cache[(model, instance.pk)] = data
-    return TemplateObject(data, model, state, full=True)
+    batch = _Batch(model, [instance.pk], state, state.cache, instance=instance)
+    state.cache[(model, instance.pk)] = batch
+    return TemplateObject({'id': instance.pk}, model, state, batch=batch)
 
 
 def get_template_objects(queryset, state):
@@ -107,11 +112,11 @@ def get_query_function(state):
 
 def get_template_context_data(value):
     """
-    Return a copy of a restricted rendering context for display, with each TemplateObject replaced by the
-    representation it holds (fetching nothing) and each TemplateObjectList by its description.
+    Return a copy of a restricted rendering context for display, with each TemplateObject replaced by its full
+    representation and each TemplateObjectList by its description.
     """
     if isinstance(value, TemplateObject):
-        return deepcopy(value._data)
+        return deepcopy(value._get_full_data())
     if isinstance(value, TemplateObjectList):
         return repr(value)
     if isinstance(value, dict):
@@ -143,41 +148,42 @@ def template_json_default(obj):
 class TemplateObject(Mapping):
     """
     A read-only representation of a NetBox object for restricted template rendering. Behaves as a dict holding the
-    object's REST API representation. Related objects not fully represented are fetched on demand, limited to those
-    the rendering user is permitted to view.
+    object's REST API representation. Fields are loaded on demand, as are related objects not fully represented,
+    limited to those the rendering user is permitted to view.
     """
-    def __init__(self, data, model, state, full=False):
+    def __init__(self, data, model, state, batch=None, batches=None):
+        # The fields known without loading the object (e.g. its brief representation as a related object)
         self._data = data
         self._model = model
         self._state = state
-        self._full = full
+        self._batch = batch
+        self._batches = batches
         self._wrapped = {}
 
     def __getitem__(self, key):
         if key in self._wrapped:
             return self._wrapped[key]
-        if key not in self._data:
-            if (relation := self._get_reverse_relation(key)) is not None:
-                self._wrapped[key] = TemplateObjectList(relation, self._state)
-                return self._wrapped[key]
-            self._resolve()
-        value = self._data[key]
+        if key in self._data:
+            value = self._data[key]
+        else:
+            value = self._load(key)
+            if isinstance(value, TemplateObjectList):
+                self._wrapped[key] = value
+                return value
         if key not in _get_relations(self._model) and isinstance(value, (dict, list)):
-            # Return a copy, so that a template can't alter the cached representation
+            # Return a copy, so that a template can't alter the retained representation
             return deepcopy(value)
         self._wrapped[key] = self._wrap(key, value)
         return self._wrapped[key]
 
     def __iter__(self):
-        self._resolve()
-        return iter(self._data)
+        return iter(self._get_full_data())
 
     def __len__(self):
-        self._resolve()
-        return len(self._data)
+        return len(self._get_full_data())
 
     def __bool__(self):
-        # Always represents an object, so avoid resolving it (via __len__) just to test truthiness
+        # Always represents an object, so avoid loading it (via __len__) just to test truthiness
         return True
 
     def __eq__(self, other):
@@ -189,46 +195,39 @@ class TemplateObject(Mapping):
         return hash((self._model, self._data.get('id')))
 
     def __str__(self):
-        return str(self._data.get('display', ''))
+        return str(self.get('display', ''))
 
     def __repr__(self):
-        return f'<TemplateObject {self._data.get("display", "")!r}>'
+        # Avoid loading the object (e.g. while formatting an error message)
+        label = self._model._meta.label if self._model is not None else None
+        return f'<TemplateObject {label} id={self._data.get("id")!r}>'
 
-    def _get_full_data(self):
-        self._resolve()
-        return self._data
+    def _get_batch(self):
+        if self._batch is None and self._model is not None and (pk := self._data.get('id')) is not None:
+            self._batch = _get_batch(self._model, pk, self._state, self._batches)
+        return self._batch
 
-    def _resolve(self):
+    def _get_full_data(self):
         """
-        Replace a brief representation with the full one, if the rendering user is permitted to view the object.
+        Return the object's full representation, or the fields it was created with if the rendering user isn't
+        permitted to view it.
         """
-        if self._full or self._model is None or self._data.get('id') is None:
-            return
-        self._full = True
-        key = (self._model, self._data['id'])
-        cache = self._state.cache
-        if key not in cache:
-            cache[key] = _fetch_full_data(self._model, self._data['id'], self._state.user)
-        if cache[key] is not None:
-            self._data = cache[key]
-            self._wrapped = {}
-
-    def _get_reverse_relation(self, key):
+        if (batch := self._get_batch()) is not None and (data := batch.get_row(self._data['id'])) is not None:
+            return data
+        return self._data
+
+    def _load(self, key):
         """
-        Return a queryset of the related objects for an optional reverse relation (e.g. a device's interfaces).
+        Return a field the object wasn't created with (loaded for every object in its batch), or the list of objects
+        related through an optional reverse relation (e.g. a device's interfaces).
         """
-        if self._model is None or self._data.get('id') is None:
-            return None
-        serializer_class = _get_serializer_class(self._model)
-        if serializer_class is None or key not in getattr(serializer_class.Meta, 'optional_fields', ()):
-            return None
-        field = serializer_class._declared_fields.get(key)
-        if not isinstance(field, RelatedObjectsField):
-            return None
-        queryset = _get_related_objects(self._model, self._data['id'], field.relation)
-        if _get_serializer_class(queryset.model) is None or not hasattr(queryset, 'restrict'):
-            return None
-        return queryset
+        if (batch := self._get_batch()) is None:
+            raise KeyError(key)
+        pk = self._data['id']
+        if (value := batch.get(pk, key)) is _MISSING:
+            if pk is None or (value := batch.get_related(pk, key)) is None:
+                raise KeyError(key)
+        return value
 
     def _wrap(self, key, value):
         relation = _get_relations(self._model).get(key)
@@ -240,13 +239,13 @@ class TemplateObject(Mapping):
             return deepcopy(value)
         if isinstance(relation, str):
             # A generic foreign key: the related model is given by its content type field
-            model = _get_model(self._data.get(relation))
+            model = _get_model(self.get(relation))
         else:
             model = relation
         if model is not None and isinstance(value, list):
-            return [TemplateObject(item, model, self._state) for item in value]
+            return [self._wrap_object(item, model) for item in value]
         if model is not None and isinstance(value, dict):
-            return TemplateObject(value, model, self._state)
+            return self._wrap_object(value, model)
         return deepcopy(value)
 
     def _wrap_generic_object(self, item):
@@ -254,7 +253,12 @@ class TemplateObject(Mapping):
             return deepcopy(item)
         if (model := _get_model(item.get('object_type'))) is None:
             return deepcopy(item)
-        return {**deepcopy(item), 'object': TemplateObject(item['object'], model, self._state)}
+        return {**deepcopy(item), 'object': self._wrap_object(item['object'], model)}
+
+    def _wrap_object(self, data, model):
+        # A related object is retained for as long as this one
+        batches = self._batches if self._batch is None else self._batch.batches
+        return TemplateObject(data, model, self._state, batches=batches)
 
 
 class TemplateObjectList:
@@ -262,14 +266,18 @@ class TemplateObjectList:
     A lazy, read-only list of TemplateObjects, limited to the objects the rendering user is permitted to view. Objects
     are loaded in chunks as the list is iterated, so a long list is never held in memory as a whole.
     """
-    def __init__(self, queryset, state, limit=None, max_results=None, pks=None):
-        queryset = queryset.restrict(state.user, 'view')
-        # Order an unordered queryset, so that the objects returned are deterministic
-        self._queryset = queryset if queryset.ordered else queryset.order_by('pk')
+    def __init__(self, queryset, state, limit=None, max_results=None, pks=None, batches=None):
+        # Given the keys of its objects, the list never evaluates the queryset
+        if pks is None:
+            queryset = queryset.restrict(state.user, 'view')
+            # Order an unordered queryset, so that the objects returned are deterministic
+            queryset = queryset if queryset.ordered else queryset.order_by('pk')
+        self._queryset = queryset
         self._state = state
         self._limit = limit
         self._max_results = max_results
         self._pks = pks
+        self._batches = batches
         # The loaded objects, retained only for a list which fits in one chunk
         self._items = None
         self._first = None
@@ -303,7 +311,7 @@ class TemplateObjectList:
         if self._items is not None:
             if isinstance(index, slice):
                 items = self._items[index]
-                sliced = TemplateObjectList(self._queryset, self._state, pks=[item['id'] for item in items])
+                sliced = self._slice([item['id'] for item in items])
                 sliced._items = items
                 return sliced
             return self._items[index]
@@ -320,7 +328,7 @@ class TemplateObjectList:
             self._check_max_results()
         pks = self._get_pks(stop)
         if isinstance(index, slice):
-            return TemplateObjectList(self._queryset, self._state, pks=pks[index])
+            return self._slice(pks[index])
         return self._load([pks[index]], cache=True)[0]
 
     def __repr__(self):
@@ -378,7 +386,196 @@ class TemplateObjectList:
         return list(dict.fromkeys(queryset))
 
     def _load(self, pks, cache=False):
-        return _load_objects(self._queryset.model, pks, self._state, cache=cache)
+        return _load_objects(self._queryset.model, pks, self._state, cache=cache, batches=self._batches)
+
+    def _slice(self, pks):
+        return TemplateObjectList(self._queryset, self._state, pks=pks, batches=self._batches)
+
+
+class _Batch:
+    """
+    A group of objects of one model which are loaded together. Each field of their REST API representations is
+    serialized for all of the objects at once, when a template first reads it from any of them.
+    """
+    def __init__(self, model, pks, state, batches, instance=None):
+        self.model = model
+        self.pks = pks
+        self.state = state
+        # Maps (model, pk) to the batch of each object retained for as long as these
+        self.batches = batches
+        # An object which the caller has ensured the user may view, used as is if the viewset's queryset omits it
+        self.instance = instance
+        self._instances = None
+        self._columns = {}
+        self._rows = None
+        self._related = {}
+
+    def get(self, pk, name):
+        """
+        Return the value of a field for the object with the given primary key, or _MISSING if it has none.
+        """
+        fields = _get_serializer(self.model, self.state)[1]
+        if self._rows is None and fields is None:
+            self._load_rows()
+        if self._rows is not None:
+            return self._rows[pk].get(name, _MISSING) if pk in self._rows else _MISSING
+        if name not in fields:
+            return _MISSING
+        if name not in self._columns:
+            self._load_column(name, fields[name])
+        return self._columns[name].get(pk, _MISSING)
+
+    def get_row(self, pk):
+        """
+        Return the full representation of the object with the given primary key, or None if the user may not view it.
+        """
+        if self._rows is None:
+            self._load_rows()
+        return self._rows.get(pk)
+
+    def get_related(self, pk, name):
+        """
+        Return the list of objects related to an object through an optional reverse relation, or None if the name
+        isn't one.
+        """
+        if name not in self._related:
+            self._related[name] = self._load_related(name)
+        if self._related[name] is None:
+            return None
+        queryset, pks, pending = self._related[name]
+        if pk in pending:
+            # Group the objects of this list with those of the lists which follow, so that they are loaded together
+            parent_pks, count = [pk], len(pks[pk])
+            for parent_pk in pending:
+                if parent_pk != pk:
+                    if (count := count + len(pks[parent_pk])) > TEMPLATE_OBJECTS_CHUNK_SIZE:
+                        break
+                    parent_pks.append(parent_pk)
+            for parent_pk in parent_pks:
+                del pending[parent_pk]
+            related = [related_pk for parent_pk in parent_pks for related_pk in pks[parent_pk]]
+            _register(queryset.model, related, self.state, self.batches)
+        return TemplateObjectList(queryset, self.state, pks=pks.get(pk, []), batches=self.batches)
+
+    def get_instances(self):
+        """
+        Return the objects which the rendering user is permitted to view, by primary key.
+        """
+        if self._instances is None:
+            queryset = self._get_queryset()
+            if hasattr(queryset, 'annotate_config_context_data'):
+                # Config context data is loaded only where it's rendered, as by the model's viewset
+                queryset = queryset.defer('_config_context_data')
+            self._instances = self._fetch(queryset)
+        return self._instances
+
+    def _get_queryset(self):
+        # Start from the REST API viewset's queryset, which may annotate fields the serializer renders
+        queryset = _get_base_queryset(self.model).filter(pk__in=self.pks)
+        if self.instance is not None:
+            return queryset
+        return queryset.restrict(self.state.user, 'view') if hasattr(queryset, 'restrict') else queryset.none()
+
+    def _fetch(self, queryset):
+        instances = {instance.pk: instance for instance in queryset}
+        if self.instance is not None and not instances:
+            # Keyed as requested, since deleting an object clears its primary key
+            instances[self.pks[0]] = self.instance
+        return instances
+
+    def _prepare(self, fields=None):
+        """
+        Return the objects by primary key, with the annotations and prefetches which the REST API uses to serialize
+        the given fields (by default, all of them).
+        """
+        serializer_class = _get_serializer_class(self.model)
+        names = set(get_fields_for_serializer(serializer_class, fields))
+        base_queryset = _get_base_queryset(self.model)
+        annotations = get_annotations_for_serializer(serializer_class, fields)
+        if 'config_context' in names and hasattr(base_queryset, 'get_config_context_data_expression'):
+            annotations['config_context_data'] = base_queryset.get_config_context_data_expression(
+                only_invalidated=True
+            )
+        prefetches = [
+            *_get_declared_prefetches(self.model, names),
+            *get_prefetches_for_serializer(serializer_class, fields),
+        ]
+        # Skip any annotations the viewset's queryset already carries
+        if annotations := {
+            name: annotation for name, annotation in annotations.items()
+            if name not in base_queryset.query.annotations
+        }:
+            # Annotated fields are serialized from objects of their own
+            return self._fetch(self._get_queryset().annotate(**annotations).prefetch_related(*prefetches))
+        instances = self.get_instances()
+        if prefetches and instances:
+            prefetch_related_objects(list(instances.values()), *prefetches)
+        return instances
+
+    def _load_column(self, name, field):
+        column = {}
+        instances = self._prepare((name,))
+        _preload_custom_field_objects(field, instances.values())
+        for pk, instance in instances.items():
+            if (value := _serialize_field(field, instance)) is not _MISSING:
+                column[pk] = to_template_data(value)
+        self._columns[name] = column
+
+        # Group the related objects which this field represents, so that they too are loaded together
+        if (relation := _get_relations(self.model).get(name)) is not None:
+            found = {}
+            for pk, value in column.items():
+                data = {name: value}
+                if isinstance(relation, str):
+                    data[relation] = self.get(pk, relation)
+                _find_related_objects(self.model, data, found)
+            self._register_related(found)
+
+    def _load_rows(self):
+        serializer = _get_serializer(self.model, self.state)[0]
+        instances = self._prepare()
+        _preload_custom_field_objects(serializer.fields.get('custom_fields'), instances.values())
+        self._rows = {
+            pk: to_template_data(serializer.to_representation(instance))
+            for pk, instance in instances.items()
+        }
+        found = {}
+        for row in self._rows.values():
+            _find_related_objects(self.model, row, found)
+        self._register_related(found)
+
+    def _register_related(self, found):
+        for model, pks in found.items():
+            _register(model, pks, self.state, self.batches)
+
+    def _load_related(self, name):
+        """
+        Return the queryset of an optional reverse relation (e.g. a device's interfaces), the primary keys of the
+        related objects the user may view for each object in the batch, and the objects whose lists are short enough
+        to be retained but have yet to be read. Return None if the name isn't one.
+        """
+        serializer_class = _get_serializer_class(self.model)
+        field = serializer_class._declared_fields.get(name)
+        if name not in getattr(serializer_class.Meta, 'optional_fields', ()) or not isinstance(
+            field, RelatedObjectsField
+        ):
+            return None
+        queryset, parent = _get_related_objects(self.model, self.pks, field.relation)
+        if _get_serializer_class(queryset.model) is None or not hasattr(queryset, 'restrict'):
+            return None
+        queryset = queryset.restrict(self.state.user, 'view')
+        # Order an unordered queryset, so that the objects returned are deterministic
+        queryset = queryset if queryset.ordered else queryset.order_by('pk')
+        pks = {}
+        for parent_pk, pk in queryset.values_list(parent, 'pk'):
+            # A dict removes any duplicates (e.g. from a distinct queryset ordered by a related field)
+            pks.setdefault(parent_pk, {})[pk] = None
+        pks = {parent_pk: list(related) for parent_pk, related in pks.items()}
+        pending = dict.fromkeys(
+            parent_pk for parent_pk in self.pks
+            if parent_pk in pks and len(pks[parent_pk]) <= TEMPLATE_OBJECTS_CHUNK_SIZE
+        )
+        return queryset, pks, pending
 
 
 #
@@ -484,21 +681,22 @@ def _get_filter_value(name, value):
     )
 
 
-def _get_related_objects(model, pk, relation):
+def _get_related_objects(model, pks, relation):
     """
-    Return a queryset of the objects related to an object through a reverse relation, a many-to-many field, or a
-    GenericRelation.
+    Return a queryset of the objects related to any of the given objects through a reverse relation, a many-to-many
+    field, or a GenericRelation, and the name of the field which holds the primary key of the object each relates to.
     """
     field = getattr(model, relation).field
     if isinstance(field, GenericRelation):
         return _get_base_queryset(field.related_model).filter(**{
             field.content_type_field_name: ContentType.objects.get_for_model(model),
-            field.object_id_field_name: pk,
-        })
+            f'{field.object_id_field_name}__in': pks,
+        }), field.object_id_field_name
     if field.model is model and field.many_to_many:
         # A many-to-many field declared on this model
-        return _get_base_queryset(field.related_model).filter(**{field.related_query_name(): pk})
-    return _get_base_queryset(field.model).filter(**{field.name: pk})
+        name = field.related_query_name()
+        return _get_base_queryset(field.related_model).filter(**{f'{name}__in': pks}), name
+    return _get_base_queryset(field.model).filter(**{f'{field.name}__in': pks}), field.attname
 
 
 def _get_relations(model):
@@ -529,62 +727,118 @@ def _get_relations(model):
     return relations
 
 
-def _prepare_queryset(queryset, serializer_class):
+def _find_related_objects(model, data, found):
     """
-    Apply the prefetches and annotations which the REST API uses to serialize the given objects.
+    Add the primary keys of the related objects represented within an object's (possibly partial) representation to
+    found, by model.
     """
-    model = queryset.model
-    fields = set(get_fields_for_serializer(serializer_class))
-    annotations = get_annotations_for_serializer(serializer_class)
-    if 'config_context' in fields and hasattr(queryset, 'get_config_context_data_expression'):
-        annotations['config_context_data'] = queryset.get_config_context_data_expression(only_invalidated=True)
-    # Skip any annotations the queryset already carries (e.g. counts applied by a list view)
-    if annotations := {
-        name: annotation for name, annotation in annotations.items() if name not in queryset.query.annotations
-    }:
-        queryset = queryset.annotate(**annotations)
-    if prefetches := [*_get_declared_prefetches(model, fields), *get_prefetches_for_serializer(serializer_class)]:
-        queryset = queryset.prefetch_related(*prefetches)
-    return queryset
+    for key, relation in _get_relations(model).items():
+        if (value := data.get(key)) is None:
+            continue
+        values = value if isinstance(value, list) else [value]
+        if relation is _GENERIC_OBJECTS:
+            items = [
+                (_get_model(item.get('object_type')), item.get('object')) for item in values if isinstance(item, dict)
+            ]
+        else:
+            # A generic foreign key gives the related model by its content type field
+            related_model = _get_model(data.get(relation)) if isinstance(relation, str) else relation
+            items = [(related_model, item) for item in values]
+        for related_model, item in items:
+            if related_model is not None and isinstance(item, dict) and item.get('id') is not None:
+                found.setdefault(related_model, {})[item['id']] = None
+                _find_related_objects(related_model, item, found)
+
 
+def _find_batch(model, pk, state, batches):
+    batch = batches.get((model, pk))
+    if batch is None and batches is not state.cache:
+        batch = state.cache.get((model, pk))
+    return batch
 
-def _fetch_full_data(model, pk, user):
+
+def _register(model, pks, state, batches):
     """
-    Return the full representation of an object, or None if the user may not view it.
+    Group any of the given objects not yet in a batch into batches, to be loaded together.
     """
-    serializer_class = _get_serializer_class(model)
-    # Start from the REST API viewset's queryset, which may annotate fields the serializer renders
-    queryset = _get_base_queryset(model).all()
-    if serializer_class is None or not hasattr(queryset, 'restrict'):
-        return None
-    queryset = _prepare_queryset(queryset.restrict(user, 'view').filter(pk=pk), serializer_class)
-    if (instance := queryset.first()) is None:
+    if _get_serializer_class(model) is None:
+        return
+    pks = [pk for pk in pks if _find_batch(model, pk, state, batches) is None]
+    for start in range(0, len(pks), TEMPLATE_OBJECTS_CHUNK_SIZE):
+        batch = _Batch(model, pks[start:start + TEMPLATE_OBJECTS_CHUNK_SIZE], state, batches)
+        for pk in batch.pks:
+            batches[(model, pk)] = batch
+
+
+def _get_batch(model, pk, state, batches=None):
+    """
+    Return the batch of the given object, or None if its model has no REST API serializer.
+    """
+    if batches is None:
+        batches = state.cache
+    if (batch := _find_batch(model, pk, state, batches)) is None:
+        _register(model, [pk], state, batches)
+        batch = batches.get((model, pk))
+    return batch
+
+
+def _get_serializer(model, state):
+    """
+    Return the serializer used for the model's objects throughout a render, and its readable fields by name. The
+    fields are None for a serializer which customizes its representation, which can only be rendered as a whole.
+    """
+    if model not in state.serializers:
+        serializer = _get_serializer_class(model)(context={'request': None})
+        fields = None
+        if type(serializer).to_representation is Serializer.to_representation:
+            fields = {name: field for name, field in serializer.fields.items() if not field.write_only}
+        state.serializers[model] = (serializer, fields)
+    return state.serializers[model]
+
+
+def _preload_custom_field_objects(field, instances):
+    """
+    Load the targets of the given objects' object and multi-object custom fields together, as the REST API does when
+    serializing a list. The serializer is shared by every batch of its model, so the targets are added to its cache.
+    """
+    from extras.api.customfields import CustomFieldsDataField
+
+    if isinstance(field, CustomFieldsDataField):
+        field.parent.context.setdefault('cf_object_cache', {}).update(field.get_object_cache(instances))
+
+
+def _serialize_field(field, instance):
+    """
+    Return a serializer field's representation of an object, as Serializer.to_representation() derives it.
+    """
+    try:
+        attribute = field.get_attribute(instance)
+    except SkipField:
+        return _MISSING
+    if (attribute.pk if isinstance(attribute, PKOnlyObject) else attribute) is None:
         return None
-    return _serialize(serializer_class, instance)
+    return field.to_representation(attribute)
 
 
-def _load_objects(model, pks, state, cache=False):
+def _load_objects(model, pks, state, cache=False, batches=None):
     """
-    Serialize the objects with the given primary keys in one batch, returning a list of full TemplateObjects in the
-    order of the keys, limited to those the rendering user is permitted to view. If cache is True, add their
-    representations to the render's cache.
+    Return TemplateObjects for the objects with the given primary keys which the rendering user is permitted to view,
+    in the order of the keys. The objects are loaded together. If cache is True, they are retained in the given
+    batches (by default, for the rest of the render); otherwise, only for as long as they are referenced.
     """
-    queryset = _get_base_queryset(model)
-    if not pks or (serializer_class := _get_serializer_class(model)) is None or not hasattr(queryset, 'restrict'):
+    if not pks or _get_serializer_class(model) is None:
         return []
-    # Load the objects from the REST API viewset's queryset, which may annotate fields the serializer renders
-    queryset = queryset.restrict(state.user, 'view').filter(pk__in=pks)
-    instances = _prepare_queryset(queryset, serializer_class)
-    data = {item['id']: item for item in _serialize(serializer_class, list(instances), many=True)}
-    if cache:
-        for pk, item in data.items():
-            if state.cache.get((model, pk)) is None:
-                state.cache[(model, pk)] = item
-    return [TemplateObject(data[pk], model, state, full=True) for pk in pks if pk in data]
-
-
-def _serialize(serializer_class, instance, many=False):
-    return to_template_data(serializer_class(instance, many=many, context={'request': None}).data)
+    if not cache:
+        batches = {}
+    elif batches is None:
+        batches = state.cache
+    _register(model, pks, state, batches)
+    objects = []
+    for pk in pks:
+        batch = _find_batch(model, pk, state, batches)
+        if pk in batch.get_instances():
+            objects.append(TemplateObject({'id': pk}, model, state, batch=batch))
+    return objects
 
 
 def to_template_data(value, state=None):

+ 174 - 5
netbox/utilities/tests/test_template_objects.py

@@ -14,12 +14,15 @@ from jinja2.sandbox import SecurityError
 
 from core.models import ObjectType
 from dcim.models import Cable, Device, Interface, Location, Site
-from extras.models import SavedFilter
-from ipam.models import IPAddress
+from extras.choices import CustomFieldTypeChoices
+from extras.models import CustomField, SavedFilter
+from ipam.models import VLAN, IPAddress
 from tenancy.models import Tenant, TenantGroup
 from users.models import ObjectPermission, User
 from utilities.jinja2 import RestrictedRenderState, render_jinja2
 from utilities.template_objects import (
+    _Batch,
+    _get_related_objects,
     _load_objects,
     get_template_context_data,
     get_template_object,
@@ -57,6 +60,11 @@ class TemplateObjectTest(TestCase):
         context = {name: get_template_object(obj, state) for name, obj in objects.items()}
         return render_jinja2(template_code, context, restricted=state)
 
+    def test_repr_does_not_load(self):
+        template_object = get_template_object(self.device, RestrictedRenderState(self.superuser))
+        with self.assertNumQueries(0):
+            self.assertEqual(repr(template_object), f'<TemplateObject dcim.Device id={self.device.pk}>')
+
     def test_fields(self):
         cases = (
             ('{{ object.name }}', 'Device 1'),
@@ -109,9 +117,9 @@ class TemplateObjectTest(TestCase):
         }
         # Resolving a related object doesn't change the representation shown
         render_jinja2('{{ device.tenant.group.slug }}', context, restricted=state)
-        with self.assertNumQueries(0):
-            data = get_template_context_data(context)
+        data = get_template_context_data(context)
         self.assertEqual(data['device']['name'], 'Device 1')
+        self.assertEqual(data['device']['status'], {'value': 'active', 'label': 'Active'})
         self.assertNotIn('group', data['device']['tenant'])
         self.assertEqual(data['interfaces'], '<TemplateObjectList dcim.Interface>')
         self.assertEqual(data['extra']['items'][1], 1)
@@ -153,6 +161,7 @@ class TemplateObjectTest(TestCase):
     def test_truthiness_does_not_fetch(self):
         state = RestrictedRenderState(self.superuser)
         context = {'object': get_template_object(self.device, state)}
+        render_jinja2('{{ object.tenant is none }}', context, restricted=state)
         with CaptureQueriesContext(connection) as queries:
             output = render_jinja2(
                 '{% if object.tenant %}{{ object.tenant.name }}{% endif %}', context, restricted=state
@@ -160,6 +169,40 @@ class TemplateObjectTest(TestCase):
         self.assertEqual(output, 'Tenant 1')
         self.assertEqual(len(queries), 0)
 
+    def test_fields_load_on_demand(self):
+        state = RestrictedRenderState(self.superuser)
+        device = get_template_object(self.device, state)
+        with self.assertNumQueries(0):
+            self.assertEqual(device['id'], self.device.pk)
+        # The object is loaded when a field is first read, and related objects when a field representing them is
+        with self.assertNumQueries(1):
+            self.assertEqual(device['name'], 'Device 1')
+        with self.assertNumQueries(0):
+            self.assertEqual(device['status'], {'value': 'active', 'label': 'Active'})
+        with self.assertNumQueries(1):
+            self.assertEqual(device['tenant']['name'], 'Tenant 1')
+
+    def test_deleted_object(self):
+        site = Site.objects.create(name='Site 2', slug='site-2')
+        state = RestrictedRenderState(self.superuser)
+        context = {'object': get_template_object(site, state)}
+        site.delete()
+        self.assertEqual(render_jinja2('{{ object.name }} {{ object }}', context, restricted=state), 'Site 2 Site 2')
+
+    def test_fields_match_full_representation(self):
+        """
+        A field loaded on demand has the same value as in the object's full representation.
+        """
+        interface = Interface.objects.get(device=self.device, name='eth0')
+        for instance in (self.device, self.device.site, self.tenant, interface, self.ip_address):
+            full = get_template_object(instance, RestrictedRenderState(self.superuser))._get_full_data()
+            obj = get_template_object(instance, RestrictedRenderState(self.superuser))
+            for name, value in full.items():
+                with self.subTest(model=instance._meta.label, field=name):
+                    self.assertEqual(obj._batch.get(instance.pk, name), value)
+            # The fields were each loaded on their own
+            self.assertIsNone(obj._batch._rows)
+
     def test_generic_object_references(self):
         device = create_test_device('Device 2')
         interface = Interface.objects.create(device=device, name='eth0', type='1000base-t', mtu=1400)
@@ -273,8 +316,9 @@ class TemplateObjectTest(TestCase):
     def test_loaded_objects_are_cached(self):
         state = RestrictedRenderState(self.superuser)
         context = {'ip': get_template_object(self.ip_address, state)}
-        render_jinja2('{% for i in object.interfaces %}{% endfor %}', {
+        render_jinja2('{% for i in object.interfaces %}{{ i.mtu }}{% endfor %}{{ ip.assigned_object }}', {
             'object': get_template_object(self.device, state),
+            **context,
         }, restricted=state)
         with CaptureQueriesContext(connection) as queries:
             output = render_jinja2('{{ ip.assigned_object.mtu }}', context, restricted=state)
@@ -289,6 +333,22 @@ class TemplateObjectTest(TestCase):
             self.assertEqual(interfaces.first()['name'], 'eth0')
         self.assertEqual(len(queries), 0)
 
+    def test_many_to_many_relations(self):
+        interfaces = list(Interface.objects.filter(device=self.device).order_by('name'))
+        vlans = (VLAN.objects.create(vid=1, name='VLAN 1'), VLAN.objects.create(vid=2, name='VLAN 2'))
+        interfaces[0].tagged_vlans.set(vlans)
+        interfaces[1].tagged_vlans.set(vlans[:1])
+
+        # From the model declaring the field, and from the model it relates to
+        queryset, parent = _get_related_objects(Interface, [interface.pk for interface in interfaces], 'tagged_vlans')
+        self.assertEqual(queryset.model, VLAN)
+        self.assertCountEqual(queryset.values_list(parent, 'pk'), [
+            (interfaces[0].pk, vlans[0].pk), (interfaces[0].pk, vlans[1].pk), (interfaces[1].pk, vlans[0].pk),
+        ])
+        queryset, parent = _get_related_objects(VLAN, [vlans[1].pk], 'interfaces_as_tagged')
+        self.assertEqual(queryset.model, Interface)
+        self.assertCountEqual(queryset.values_list(parent, 'pk'), [(vlans[1].pk, interfaces[0].pk)])
+
     def test_reverse_relations_are_restricted(self):
         user = User.objects.create_user(username='user')
         grant_view(user, Interface, {'name': 'eth1'})
@@ -384,6 +444,115 @@ class TemplateObjectListTest(TestCase):
             self.render(template_code, Device.objects.all())
         self.assertEqual(len(queries), query_count)
 
+    def test_custom_field_objects_load_together(self):
+        """
+        The targets of object and multi-object custom fields are loaded for all of the objects at once.
+        """
+        device_type = ObjectType.objects.get_for_model(Device)
+        site_type = ObjectType.objects.get_for_model(Site)
+        for name, cf_type in (('cf_site', CustomFieldTypeChoices.TYPE_OBJECT),
+                              ('cf_sites', CustomFieldTypeChoices.TYPE_MULTIOBJECT)):
+            cf = CustomField.objects.create(name=name, type=cf_type, related_object_type=site_type)
+            cf.object_types.set([device_type])
+
+        def create_device(i):
+            device = create_test_device(f'Device {i}', site=self.sites[0])
+            device.custom_field_data = {
+                'cf_site': self.sites[i % 2].pk,
+                'cf_sites': [site.pk for site in self.sites],
+            }
+            device.save()
+
+        # Read the custom_fields field alone, and the full representation
+        template_codes = (
+            '{% for d in objects %}{{ d.custom_fields.cf_site.slug }}'
+            '{% for s in d.custom_fields.cf_sites %}{{ s.slug }}{% endfor %} {% endfor %}',
+            '{% for d in objects %}{{ d | tojson | length > 0 }}{% endfor %}',
+        )
+        create_device(1)
+        query_counts = []
+        for template_code in template_codes:
+            with CaptureQueriesContext(connection) as queries:
+                output = self.render(template_code, Device.objects.order_by('name'))
+            query_counts.append(len(queries))
+        self.assertEqual(output, 'True')
+
+        for i in range(2, 5):
+            create_device(i)
+        self.assertEqual(
+            self.render(template_codes[0], Device.objects.order_by('name')),
+            'site-2site-1site-2 site-1site-1site-2 site-2site-1site-2 site-1site-1site-2 ',
+        )
+        for template_code, query_count in zip(template_codes, query_counts):
+            with CaptureQueriesContext(connection) as queries:
+                self.render(template_code, Device.objects.order_by('name'))
+            self.assertEqual(len(queries), query_count)
+
+    def test_related_objects_load_together(self):
+        """
+        Related objects and reverse relations are loaded for all of the objects at once.
+        """
+        template_code = (
+            '{% for d in objects %}{{ d.tenant.group.slug }}{{ d.site.status.value }}'
+            '{% for i in d.interfaces %}{{ i.name }}{{ i.mtu }}{{ i.device.role.color }}{% endfor %}'
+            '{{ d.interfaces.count() }}{{ d.interfaces.first().type.value }}{% endfor %}'
+        )
+
+        def create_device(i):
+            group = TenantGroup.objects.create(name=f'Tenant Group {i}', slug=f'tenant-group-{i}')
+            tenant = Tenant.objects.create(name=f'Tenant {i}', slug=f'tenant-{i}', group=group)
+            device = create_test_device(f'Device {i}', site=self.sites[i % 2], tenant=tenant)
+            Interface.objects.bulk_create([
+                Interface(device=device, name=f'eth{n}', type='1000base-t', mtu=1500) for n in range(i)
+            ])
+
+        create_device(1)
+        with CaptureQueriesContext(connection) as queries:
+            output = self.render(template_code, Device.objects.order_by('name'))
+        self.assertEqual(output, 'tenant-group-1activeeth015009e9e9e11000base-t')
+        query_count = len(queries)
+
+        for i in range(2, 5):
+            create_device(i)
+        with CaptureQueriesContext(connection) as queries:
+            self.render(template_code, Device.objects.order_by('name'))
+        self.assertEqual(len(queries), query_count)
+
+    def test_only_fields_read_are_loaded(self):
+        create_test_device('Device 1', site=self.sites[0])
+        # The primary keys of the objects, then the objects themselves
+        with self.assertNumQueries(2):
+            output = self.render('{% for d in objects %}{{ d.name }}{% endfor %}', Device.objects.all())
+        self.assertEqual(output, 'Device 1')
+
+    @patch('utilities.template_objects.TEMPLATE_OBJECTS_CHUNK_SIZE', 2)
+    def test_reverse_relations_are_grouped_as_read(self):
+        devices = [create_test_device(f'Device {i}', site=self.sites[0]) for i in range(1, 4)]
+        interfaces = [Interface.objects.create(device=device, name='eth0', type='1000base-t') for device in devices]
+        state = RestrictedRenderState(self.superuser)
+        batch = _Batch(Device, [device.pk for device in devices], state, state.cache)
+
+        # Reading a list groups its objects with those of the lists which follow, up to one chunk
+        batch.get_related(devices[0].pk, 'interfaces')
+        self.assertEqual(set(state.cache), {(Interface, interfaces[0].pk), (Interface, interfaces[1].pk)})
+        self.assertIs(state.cache[(Interface, interfaces[0].pk)], state.cache[(Interface, interfaces[1].pk)])
+        batch.get_related(devices[2].pk, 'interfaces')
+        self.assertIn((Interface, interfaces[2].pk), state.cache)
+
+    @patch('utilities.template_objects.TEMPLATE_OBJECTS_CHUNK_SIZE', 2)
+    def test_long_lists_retain_nothing(self):
+        for i in range(1, 4):
+            device = create_test_device(f'Device {i}', site=self.sites[i % 2])
+            Interface.objects.create(device=device, name='eth0', type='1000base-t')
+        state = RestrictedRenderState(self.superuser)
+        output = render_jinja2(
+            '{% for d in objects %}{{ d.site.status.value }}{{ d.interfaces.first().name }} {% endfor %}',
+            {'objects': get_template_objects(Device.objects.all(), state)},
+            restricted=state,
+        )
+        self.assertEqual(output, 'activeeth0 activeeth0 activeeth0 ')
+        self.assertEqual(state.cache, {})
+
 
 class QueryTest(TestCase):