|
|
@@ -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):
|