Browse Source

Merge pull request #23728 from netbox-community/23721-has-interfaces-filter-exists

Closes #23721: Use an EXISTS subquery for the device interfaces filter
bctiemann 10 hours ago
parent
commit
210977e6ee
2 changed files with 25 additions and 3 deletions
  1. 6 2
      netbox/dcim/filtersets.py
  2. 19 1
      netbox/dcim/tests/test_filtersets.py

+ 6 - 2
netbox/dcim/filtersets.py

@@ -1,7 +1,7 @@
 import django_filters
 import netaddr
 from django.contrib.contenttypes.models import ContentType
-from django.db.models import Func, IntegerField, Q
+from django.db.models import Exists, Func, IntegerField, OuterRef, Q
 from django.utils.translation import gettext as _
 from drf_spectacular.types import OpenApiTypes
 from drf_spectacular.utils import extend_schema_field
@@ -1682,7 +1682,11 @@ class DeviceFilterSet(
         return queryset.exclude(poweroutlets__isnull=value)
 
     def _interfaces(self, queryset, name, value):
-        return queryset.exclude(interfaces__isnull=value)
+        # Query Interface directly. Excluding on interfaces__isnull self-joins Device, which
+        # PostgreSQL can plan very poorly when most devices have no interfaces (#23721).
+        # False uses ~Exists too: a pk__in subquery would negate to NOT IN, which PostgreSQL can't run as an anti join.
+        has_interfaces = Exists(Interface.objects.filter(device=OuterRef('pk')))
+        return queryset.filter(has_interfaces if value else ~has_interfaces)
 
     def _pass_through_ports(self, queryset, name, value):
         return queryset.exclude(

+ 19 - 1
netbox/dcim/tests/test_filtersets.py

@@ -1,9 +1,10 @@
+import re
 from decimal import Decimal
 
 from django.conf import settings
 from django.contrib.contenttypes.models import ContentType
 from django.db import DEFAULT_DB_ALIAS, connection
-from django.test import TestCase
+from django.test import TestCase, tag
 
 from circuits.models import Circuit, CircuitTermination, CircuitType, Provider
 from dcim.choices import *
@@ -3466,6 +3467,23 @@ class DeviceTestCase(TestCase, ChangeLoggedFilterSetTestMixin):
         params = {'interfaces': 'false'}
         self.assertEqual(self.filterset(params, self.queryset).qs.count(), 1)
 
+    @tag('performance', 'regression')
+    def test_interfaces_query_reads_only_interface_table(self):
+        """
+        Regression test for #23721: the interfaces filter must query the Interface table directly
+        rather than self-joining Device, which PostgreSQL can plan very poorly on large inventories.
+        """
+        for value in ('true', 'false'):
+            with self.subTest(interfaces=value):
+                sql = str(self.filterset({'interfaces': value}, self.queryset).qs.query)
+                # Device appears once, as the outer table, at any nesting depth
+                self.assertEqual(len(re.findall(r'(?:FROM|JOIN) "dcim_device"', sql)), 1)
+                if value == 'true':
+                    self.assertIn('EXISTS', sql)
+                    self.assertNotIn('NOT EXISTS', sql)
+                else:
+                    self.assertIn('NOT EXISTS', sql)
+
     def test_pass_through_ports(self):
         params = {'pass_through_ports': 'true'}
         self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)