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

Closes #23289: Prefetch parent devices in device API (#23814)

Avoid N+1 queries when listing installed child devices by prefetching
their parents along with device types, manufacturers, and virtual
chassis used to resolve unnamed parents' display names.

Add separate query-count regression tests for named parents, unnamed
parents, and unnamed parents in a virtual chassis.
Shashwat Pratap SIngh 1 день назад
Родитель
Сommit
36bacf3b63
2 измененных файлов с 99 добавлено и 4 удалено
  1. 7 1
      netbox/dcim/api/views.py
  2. 92 3
      netbox/dcim/tests/test_api.py

+ 7 - 1
netbox/dcim/api/views.py

@@ -460,7 +460,13 @@ class DeviceViewSet(ConfigContextQuerySetMixin, RenderConfigMixin, NetBoxModelVi
     field_prefetches = {
         # Read by Device.__str__() for unnamed devices and by config context rendered without its annotation
         ('display', 'config_context'): ('device_type__manufacturer',),
-        ('parent_device',): ('parent_bay',),
+        # Include the relations used to render the parent device's display name
+        ('parent_device',): (
+            Prefetch(
+                'parent_bay__device',
+                queryset=Device.objects.select_related('device_type__manufacturer', 'virtual_chassis'),
+            ),
+        ),
     }
 
 

+ 92 - 3
netbox/dcim/tests/test_api.py

@@ -9,7 +9,7 @@ from django.conf import settings
 from django.contrib.contenttypes.models import ContentType
 from django.contrib.contenttypes.prefetch import GenericPrefetch
 from django.db import connection
-from django.db.models import FETCH_PEERS, prefetch_related_objects
+from django.db.models import FETCH_PEERS, Prefetch, prefetch_related_objects
 from django.test import override_settings, tag
 from django.test.utils import CaptureQueriesContext
 from django.urls import reverse
@@ -2835,7 +2835,13 @@ class DeviceTestCase(Mixins.FieldPrefetchMixin, APIViewTestCases.APIViewTestCase
         'omit=parent_device', 'fields=id,parent_device&omit=parent_device', 'brief=1&omit=display',
         'brief=1&fields=id,config_context',
     )
-    eager_prefetches = ('device_type__manufacturer', 'parent_bay')
+    eager_prefetches = (
+        'device_type__manufacturer',
+        Prefetch(
+            'parent_bay__device',
+            queryset=Device.objects.select_related('device_type__manufacturer', 'virtual_chassis'),
+        ),
+    )
     brief_fields = ['description', 'display', 'id', 'name', 'url']
     bulk_update_data = {
         'status': 'failed',
@@ -2957,7 +2963,10 @@ class DeviceTestCase(Mixins.FieldPrefetchMixin, APIViewTestCases.APIViewTestCase
         filters = []
         for i in range(2):
             site = Site.objects.create(name=f'Unit Site {i}', slug=f'unit-site-{i}')
-            parent = Device.objects.create(device_type=parent_type, role=device.role, site=site, name=f'Parent {i}')
+            # The second parent is unnamed, so its display reads the device type and manufacturer
+            parent = Device.objects.create(
+                device_type=parent_type, role=device.role, site=site, name=f'Parent {i}' if i == 0 else None
+            )
             child = Device.objects.create(device_type=child_type, role=device.role, site=site, name=f'Child {i}')
             DeviceBay.objects.create(device=parent, name='Bay 1', installed_device=child)
             # Unnamed, so its display reads the device type and manufacturer
@@ -2965,6 +2974,86 @@ class DeviceTestCase(Mixins.FieldPrefetchMixin, APIViewTestCases.APIViewTestCase
             filters.append(f'site_id={site.pk}')
         return [filters[0], '&'.join(filters)]
 
+    def _assert_parent_device_query_count(self, create_parent):
+        """
+        Assert that listing installed child devices loads their parents with the same number of queries however
+        many children are listed, each installed in a parent created by `create_parent(index, site, device_type)`.
+        """
+        self.add_permissions('dcim.view_device')
+        site = Site.objects.create(name='Parent Site', slug='parent-site')
+        device = Device.objects.get(name='Device 1')
+        parent_type = DeviceType.objects.create(
+            manufacturer=device.device_type.manufacturer, model='Query Parent Type', slug='query-parent-type',
+            subdevice_role=SubdeviceRoleChoices.ROLE_PARENT,
+        )
+        child_type = DeviceType.objects.create(
+            manufacturer=device.device_type.manufacturer, model='Query Child Type', slug='query-child-type',
+            subdevice_role=SubdeviceRoleChoices.ROLE_CHILD, u_height=0,
+        )
+        children, expected = [], {}
+        for i in range(3):
+            parent = create_parent(i, site, parent_type)
+            child = Device.objects.create(device_type=child_type, role=device.role, site=site, name=f'Query Child {i}')
+            DeviceBay.objects.create(device=parent, name='Bay 1', installed_device=child)
+            children.append(child)
+            expected[child.pk] = {'id': parent.pk, 'display': str(parent)}
+
+        def check_results(objs, results):
+            parents = {
+                result['id']: {'id': result['parent_device']['id'], 'display': result['parent_device']['display']}
+                for result in results
+            }
+            self.assertEqual(parents, {obj.pk: expected[obj.pk] for obj in objs})
+
+        assert_list_query_count_is_constant(
+            self,
+            self._get_list_url(),
+            lambda objs: {'id': [obj.pk for obj in objs], 'fields': 'id,parent_device'},
+            children,
+            check_results,
+        )
+
+    def test_list_objects_parent_device_query_count_named(self):
+        """
+        Listing children of named parents runs the same number of queries however many children are listed.
+        """
+        role = DeviceRole.objects.first()
+
+        def create_parent(index, site, device_type):
+            return Device.objects.create(
+                device_type=device_type, role=role, site=site, name=f'Query Parent {index}'
+            )
+
+        self._assert_parent_device_query_count(create_parent)
+
+    def test_list_objects_parent_device_query_count_unnamed(self):
+        """
+        Listing children of unnamed parents, displayed by their device type and manufacturer, runs the same number of
+        queries however many children are listed.
+        """
+        role = DeviceRole.objects.first()
+
+        def create_parent(index, site, device_type):
+            return Device.objects.create(device_type=device_type, role=role, site=site, name=None)
+
+        self._assert_parent_device_query_count(create_parent)
+
+    def test_list_objects_parent_device_query_count_unnamed_virtual_chassis(self):
+        """
+        Listing children of unnamed parents in a virtual chassis, displayed by their virtual chassis and position,
+        runs the same number of queries however many children are listed.
+        """
+        role = DeviceRole.objects.first()
+
+        def create_parent(index, site, device_type):
+            virtual_chassis = VirtualChassis.objects.create(name=f'Query Chassis {index}')
+            return Device.objects.create(
+                device_type=device_type, role=role, site=site, name=None,
+                virtual_chassis=virtual_chassis, vc_position=1,
+            )
+
+        self._assert_parent_device_query_count(create_parent)
+
     def test_config_context_read_without_copy(self):
         """
         REST and GraphQL read cached config context without copying it.