From e5fc23f2f31a4fbac34e04a4de99400ee8a4ff66 Mon Sep 17 00:00:00 2001 From: Jason Novinger Date: Fri, 12 Sep 2025 16:09:54 -0600 Subject: [PATCH] Fixes #20327: Device queries are now faster when including ConfidContexts Move .distinct() from main queryset to tag subquery to eliminate performance bottleneck when querying devices with config contexts. The .distinct() call on the main device queryset was causing PostgreSQL to sort all devices before pagination, resulting in 15x slower API responses for large installations (10k+ devices, 100+ config contexts). Moving .distinct() to the tag subquery eliminates duplicates at their source (GenericForeignKey tag relationships) while preserving the fix for issues #5314 and #5387 without impacting overall query performance. --- netbox/extras/querysets.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/netbox/extras/querysets.py b/netbox/extras/querysets.py index cb7c1b0aa..ee2afed4c 100644 --- a/netbox/extras/querysets.py +++ b/netbox/extras/querysets.py @@ -93,7 +93,7 @@ class ConfigContextModelQuerySet(RestrictedQuerySet): _data=EmptyGroupByJSONBAgg('data', ordering=['weight', 'name']) ).values("_data").order_by() ) - ).distinct() + ) def _get_config_context_filters(self): # Construct the set of Q objects for the specific object types @@ -117,7 +117,7 @@ class ConfigContextModelQuerySet(RestrictedQuerySet): ).values_list( 'tag_id', flat=True - ) + ).distinct() ) ) | Q(tags=None), is_active=True,