Browse Source

Load included objects from their viewset's queryset

Included objects now start from their own viewset's queryset, keeping
its lookups, annotations and fetch mode, so they don't query per object
for fields those serve (e.g. console port link peers) and carry values
it annotates (e.g. a location's rack count). The viewset is now found
under a script prefix too, get_annotations_for_serializer() takes
include after exclude, and the schema keeps a serializer's own field
selection when documenting its optional fields.
Jeremy Stretch 22 hours ago
parent
commit
2cd74e3524

+ 1 - 1
docs/integrations/rest-api.md

@@ -398,7 +398,7 @@ GET /api/dcim/devices/123/?include=interfaces.mtu,interfaces.ip_addresses&omit=i
 }
 ```
 
-A path also includes the fields along it: `include=interfaces.ip_addresses` includes `interfaces` as well. Paths are limited to three segments (e.g. `interfaces.ip_addresses.vrf`). A path passed to `include` can pass only through optional fields (such as `interfaces`), whose objects are limited to those you have permission to view, so it can't add fields to a device's `site`, for example. Paths passed to `omit` can pass through other related objects as well, but not through generic relations (such as an IP address's `assigned_object`) or other fields which don't represent a single type of object. Related object counts and other values calculated for a list (such as a location's `device_count`) aren't available on nested objects.
+A path also includes the fields along it: `include=interfaces.ip_addresses` includes `interfaces` as well. Paths are limited to three segments (e.g. `interfaces.ip_addresses.vrf`). A path passed to `include` can pass only through optional fields (such as `interfaces`), whose objects are limited to those you have permission to view, so it can't add fields to a device's `site`, for example. Paths passed to `omit` can pass through other related objects as well, but not through generic relations (such as an IP address's `assigned_object`) or other fields which don't represent a single type of object. Related object counts (such as a rack's `device_count`) and some other values calculated for a list aren't available on nested objects.
 
 An invalid path passed to `include` or `omit` returns a 400 response naming it. (Unrecognized field names passed to `fields` or `omit` are ignored.)
 

+ 3 - 1
netbox/core/api/schema.py

@@ -483,7 +483,9 @@ class NetBoxAutoSchema(AutoSchema):
         optional_fields = getattr(getattr(serializer, 'Meta', None), 'optional_fields', ())
         if direction == 'response' and optional_fields and isinstance(serializer, BaseModelSerializer) and \
                 not serializer.nested:
-            serializer = type(serializer)(context=serializer.context, include=optional_fields)
+            # Rebuild the serializer from its own arguments, to keep any fields selected
+            serializer = type(serializer)(*serializer._args, **serializer._kwargs)
+            serializer.select_fields(include=optional_fields)
             schema = super()._map_basic_serializer(serializer, direction)
             if required := [name for name in schema.get('required', []) if name not in optional_fields]:
                 schema['required'] = required

+ 77 - 4
netbox/netbox/tests/test_api.py

@@ -23,11 +23,15 @@ from core.models import DataFile, DataSource, ObjectType
 from dcim.api.serializers import DeviceSerializer, InterfaceSerializer, RackSerializer, SiteSerializer
 from dcim.api.views import DeviceTypeViewSet, SiteViewSet
 from dcim.models import (
+    Cable,
+    ConsolePort,
+    ConsoleServerPort,
     Device,
     DeviceRole,
     DeviceType,
     Interface,
     InterfaceTemplate,
+    Location,
     Manufacturer,
     Rack,
     Region,
@@ -45,8 +49,11 @@ from netbox.api.viewsets.mixins import BulkUpdateModelMixin
 from users.constants import TOKEN_PREFIX
 from users.models import ObjectPermission, Token, User
 from utilities.api import get_serializer_for_model
-from utilities.testing import APITestCase, create_test_device
+from utilities.testing import APITestCase, create_test_device, create_test_virtualmachine
+from virtualization.models import VMInterface
 from vpn.api.serializers import L2VPNSerializer
+from vpn.choices import L2VPNTypeChoices
+from vpn.models import L2VPN, L2VPNTermination
 
 
 class AppTestCase(APITestCase):
@@ -963,6 +970,72 @@ class IncludeFieldsTestCase(APITestCase):
         count_queries(sites[1])
         self.assertEqual(count_queries(sites[0]), count_queries(sites[1]))
 
+    def test_include_query_count_with_viewset_lookups(self):
+        """
+        Included objects load the lookups of their own viewset's queryset, so they add no more queries per object than
+        on their own endpoint.
+        """
+        self.add_permissions(
+            'dcim.view_device', 'dcim.view_consoleport', 'virtualization.view_virtualmachine',
+            'virtualization.view_vminterface',
+        )
+        peer_device = create_test_device('Peer Device', site=self.devices[0].site)
+        l2vpn = L2VPN.objects.create(name='L2VPN 1', slug='l2vpn-1', type=L2VPNTypeChoices.TYPE_VXLAN)
+        console_ports, virtual_machines, vm_interfaces = [], [], []
+        for i in range(len(self.devices)):
+            console_ports.append(ConsolePort.objects.create(device=self.devices[i], name='Console'))
+            peer = ConsoleServerPort.objects.create(device=peer_device, name=f'Console Server {i}')
+            Cable(a_terminations=[console_ports[i]], b_terminations=[peer]).save()
+            virtual_machines.append(create_test_virtualmachine(f'Virtual Machine {i}'))
+            vm_interfaces.append(VMInterface.objects.create(virtual_machine=virtual_machines[i], name='eth0'))
+            L2VPNTermination.objects.create(l2vpn=l2vpn, assigned_object=vm_interfaces[i])
+
+        def get_added_queries(url, objects):
+            """Return the queries listing all the objects adds to listing the first."""
+            counts = []
+            for objs in (objects, objects[:1], objects):
+                with CaptureQueriesContext(connection) as queries:
+                    data = self.get(url + ''.join(f'&id={obj.pk}' for obj in objs))
+                self.assertEqual(len(data['results']), len(objs))
+                # Token authentication refreshes last_used once a minute
+                counts.append(sum('"users_token"' not in query['sql'] for query in queries.captured_queries))
+            # The first request warms per-process caches (e.g. ContentType)
+            return counts[2] - counts[1]
+
+        devices_url = f'{reverse("dcim-api:device-list")}?include='
+        console_ports_url = f'{reverse("dcim-api:consoleport-list")}?fields=id,'
+        vms_url = f'{reverse("virtualization-api:virtualmachine-list")}?include='
+        vm_interfaces_url = f'{reverse("virtualization-api:vminterface-list")}?fields=id,'
+        for url, objects, own_url, own_objects in (
+            (f'{devices_url}console_ports.link_peers', self.devices, f'{console_ports_url}link_peers', console_ports),
+            (
+                f'{devices_url}console_ports.connected_endpoints', self.devices,
+                f'{console_ports_url}connected_endpoints', console_ports,
+            ),
+            (
+                f'{vms_url}interfaces.l2vpn_termination', virtual_machines,
+                f'{vm_interfaces_url}l2vpn_termination', vm_interfaces,
+            ),
+        ):
+            with self.subTest(url=url):
+                self.assertEqual(get_added_queries(url, objects), get_added_queries(own_url, own_objects))
+        self.assertEqual(get_added_queries(f'{devices_url}console_ports.link_peers', self.devices), 0)
+
+    def test_included_annotations(self):
+        """
+        Included objects carry the annotations of their own viewset's queryset.
+        """
+        self.add_permissions('dcim.view_site', 'dcim.view_location')
+        site = self.devices[0].site
+        location = Location.objects.create(site=site, name='Location 1', slug='location-1')
+        Rack.objects.create(site=site, location=location, name='Rack 1')
+        Device.objects.filter(pk=self.devices[0].pk).update(location=location)
+
+        url = reverse('dcim-api:site-detail', kwargs={'pk': site.pk})
+        data = self.get(f'{url}?include=locations.device_count')
+        self.assertEqual(data['locations'][0]['rack_count'], 1)
+        self.assertEqual(data['locations'][0]['device_count'], 1)
+
     def test_invalid_paths_without_permission(self):
         # Permission is checked before the paths are validated
         self.assertHttpStatus(self.client.get(f'{self.url}?include=foo', **self.header), status.HTTP_403_FORBIDDEN)
@@ -1013,11 +1086,11 @@ class IncludeFieldsTestCase(APITestCase):
         # Unrecognized top-level names to omit are ignored, as before
         self.assertIn('name', self.get(f'{self.url}?omit=foo'))
 
-        # Values which the viewset annotates aren't available on nested objects
+        # Values which the viewset annotates only on its own responses aren't available on nested objects
         self.add_permissions('dcim.view_site')
         url = reverse('dcim-api:site-list')
-        data = self.get(f'{url}?include=locations.device_count', status_code=status.HTTP_400_BAD_REQUEST)
-        self.assertTrue(data['include'][0].startswith('locations.device_count: '), data)
+        data = self.get(f'{url}?include=racks.device_count', status_code=status.HTTP_400_BAD_REQUEST)
+        self.assertTrue(data['include'][0].startswith('racks.device_count: '), data)
 
         # A viewset which overrides initial() validates the paths too
         url = reverse('core-api:objecttype-list')

+ 24 - 8
netbox/utilities/api.py

@@ -12,7 +12,7 @@ from django.core.exceptions import (
 )
 from django.db.models import Prefetch
 from django.db.models.fields.related import ManyToManyRel, ManyToOneRel, RelatedField
-from django.urls import NoReverseMatch, Resolver404, resolve, reverse
+from django.urls import NoReverseMatch, Resolver404, get_script_prefix, resolve, reverse
 from django.utils.module_loading import import_string
 from django.utils.translation import gettext_lazy as _
 from rest_framework.permissions import BasePermission
@@ -241,14 +241,18 @@ def _get_serializer_fields(serializer: Serializer):
 
 def _is_annotated_field(field, name, model):
     """
-    Return True if a declared serializer field reads an attribute which only the model's viewset annotates.
+    Return True if a declared serializer field reads a value which the model's viewset annotates only on its own
+    responses (e.g. a related object count), and which included objects therefore lack.
     """
     if isinstance(field, RelatedObjectCountField):
         return not field.fallback_source
     if not field.read_only or isinstance(field, (SerializerMethodField, RelatedObjectsField)):
         return False
-    source = field.source or name
-    return source != '*' and not hasattr(model, source.split('.')[0])
+    source = (field.source or name).split('.')[0]
+    if source == '*' or hasattr(model, source):
+        return False
+    # Included objects are loaded from the viewset's queryset, with its annotations
+    return source not in _get_base_queryset(model).query.annotations
 
 
 def get_field_path_error(serializer_class, path, omit=False):
@@ -310,11 +314,21 @@ def _get_viewset_for_model(model):
     from utilities.views import get_viewname
 
     try:
-        return resolve(reverse(get_viewname(model, 'list', rest_api=True))).func.cls
+        # resolve() expects a path without the script prefix (e.g. a WSGI SCRIPT_NAME) which reverse() adds
+        path = reverse(get_viewname(model, 'list', rest_api=True)).removeprefix(get_script_prefix())
+        return resolve(f'/{path}').func.cls
     except (NoReverseMatch, Resolver404, AttributeError):
         return None
 
 
+def _get_base_queryset(model):
+    """
+    Return the queryset of the model's REST API viewset, or the model's default queryset if it has none.
+    """
+    queryset = getattr(_get_viewset_for_model(model), 'queryset', None)
+    return queryset if queryset is not None else model._default_manager.all()
+
+
 def _get_declared_prefetches(model, fields):
     """
     Return the lookups declared by the model's REST API viewset for any of the given fields (see
@@ -331,9 +345,11 @@ def _get_declared_prefetches(model, fields):
 
 def _get_included_queryset(model, user, fields):
     """
-    Return the objects of a model which the user may view, for a RelatedObjectsField rendering the given fields.
+    Return the objects of a model which the user may view, for a RelatedObjectsField rendering the given fields. These
+    start from the model's viewset queryset, keeping its lookups, annotations and fetch mode.
     """
-    queryset = model._default_manager.restrict(user, 'view')
+    # Clone the viewset's queryset, which restrict() returns as is for a superuser
+    queryset = _get_base_queryset(model).all().restrict(user, 'view')
     # Load the config context of config context models only where rendered, as their viewsets do
     if hasattr(queryset, 'annotate_config_context_data'):
         if 'config_context' in fields:
@@ -423,7 +439,7 @@ def get_prefetches_for_serializer(
     return prefetch_fields
 
 
-def get_annotations_for_serializer(serializer_class, fields=None, omit=None, include=None, exclude=()):
+def get_annotations_for_serializer(serializer_class, fields=None, omit=None, exclude=(), include=None):
     """
     Return a mapping of attribute names to annotations to be applied to the queryset for a serializer.
     """

+ 28 - 5
netbox/utilities/tests/test_api.py

@@ -1,12 +1,16 @@
+from unittest.mock import patch
+
 from django.contrib.contenttypes.prefetch import GenericPrefetch
 from django.db.models import Prefetch
 from django.test import Client, RequestFactory, TestCase, override_settings, tag
-from django.urls import reverse
+from django.urls import reverse, set_script_prefix
 from drf_spectacular.drainage import GENERATOR_STATS
 from drf_spectacular.generators import SchemaGenerator
+from drf_spectacular.openapi import AutoSchema
 from rest_framework import status
 from rest_framework.serializers import Serializer
 
+from core.api.schema import NetBoxAutoSchema
 from core.models import ObjectType
 from dcim.api.serializers import DeviceSerializer, SiteSerializer
 from dcim.api.views import InterfaceViewSet
@@ -23,6 +27,7 @@ from netbox.registry import registry
 from users.api.serializers import UserSerializer
 from users.models import Group, ObjectPermission, User
 from utilities.api import (
+    _get_viewset_for_model,
     get_field_path_error,
     get_fields_for_serializer,
     get_prefetches_for_serializer,
@@ -516,6 +521,13 @@ class APIDocsTestCase(TestCase):
         self.assertNotIn('interfaces', components['BriefDevice']['properties'])
         self.assertNotIn('interfaces', components['WritableDeviceRequest']['properties'])
 
+    def test_schema_optional_fields_keep_selected_fields(self):
+        # A response serializer's own selection of fields is kept beside its optional fields
+        with patch.object(AutoSchema, '_map_basic_serializer', return_value={}) as map_basic_serializer:
+            NetBoxAutoSchema()._map_basic_serializer(DeviceSerializer(fields=['id', 'name']), 'response')
+        fields = map_basic_serializer.call_args.args[0].fields
+        self.assertEqual(set(fields), {'id', 'name', *DeviceSerializer.Meta.optional_fields})
+
 
 class ParseFieldPathsTestCase(TestCase):
 
@@ -584,12 +596,12 @@ class GetFieldPathErrorTestCase(TestCase):
                 self.assertEqual(get_field_path_error(DeviceSerializer, path, omit=True), error)
 
     def test_annotated_fields_on_nested_objects(self):
-        # Values which the viewset annotates (whether as related object counts or plain fields) are unavailable
+        # Values which the viewset annotates only on its own responses (e.g. related object counts) are unavailable
+        self.assertEqual(get_field_path_error(SiteSerializer, 'racks.device_count'), 'Unknown field: device_count')
+        # Those its queryset annotates are loaded with included objects
         for path in ('locations.device_count', 'locations.rack_count'):
             with self.subTest(path=path):
-                self.assertEqual(
-                    get_field_path_error(SiteSerializer, path), f'Unknown field: {path.split(".")[1]}'
-                )
+                self.assertIsNone(get_field_path_error(SiteSerializer, path))
         self.assertEqual(
             get_field_path_error(DeviceSerializer, 'site.circuit_count', omit=True), 'Unknown field: circuit_count'
         )
@@ -1018,6 +1030,17 @@ class GetPrefetchesForIncludedFieldsTestCase(APITestCase):
         self.assertEqual(list(querysets['_included_interfaces'].values_list('name', flat=True)), ['eth1'])
         self.assertEqual(querysets['_included_ip_addresses'].count(), 2)
 
+    def test_declared_prefetches_with_script_prefix(self):
+        # The viewset declaring them is found when NetBox is served beneath a script prefix (e.g. a WSGI SCRIPT_NAME)
+        _get_viewset_for_model.cache_clear()
+        set_script_prefix('/netbox/')
+        try:
+            lookups = get_prefetches_for_serializer(SiteSerializer, fields=['id'], include=['devices'], user=self.user)
+        finally:
+            set_script_prefix('/')
+            _get_viewset_for_model.cache_clear()
+        self.assertIn('_included_devices__device_type__manufacturer', lookups)
+
     def test_no_user(self):
         # Without a user to restrict them to, the objects of a RelatedObjectsField are not prefetched
         lookups = get_prefetches_for_serializer(