Skip to content

Fixes #19309: N+1 problem on /interfaces, /ip-addresses and /prefixes requests #19304

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
May 6, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions netbox/dcim/api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -455,6 +455,7 @@ class InterfaceViewSet(PathEndpointMixin, NetBoxModelViewSet):
Interface.objects.select_related("device", "cable"),
],
),
'virtual_circuit_termination',
'l2vpn_terminations', # Referenced by InterfaceSerializer.l2vpn_termination
'ip_addresses', # Referenced by Interface.count_ipaddresses()
'fhrp_group_assignments', # Referenced by Interface.count_fhrp_groups()
Expand Down
17 changes: 15 additions & 2 deletions netbox/ipam/api/views.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from copy import deepcopy

from django.contrib.contenttypes.prefetch import GenericPrefetch
from django.core.exceptions import ObjectDoesNotExist, PermissionDenied
from django.db import transaction
from django.shortcuts import get_object_or_404
Expand All @@ -13,6 +14,7 @@
from rest_framework.routers import APIRootView
from rest_framework.views import APIView

from dcim.models import Interface
from ipam import filtersets
from ipam.models import *
from ipam.utils import get_next_available_prefix
Expand All @@ -21,6 +23,7 @@
from netbox.config import get_config
from netbox.constants import ADVISORY_LOCK_KEYS
from utilities.api import get_serializer_for_model
from virtualization.models import VMInterface
from . import serializers


Expand Down Expand Up @@ -79,7 +82,7 @@ class RoleViewSet(NetBoxModelViewSet):


class PrefixViewSet(NetBoxModelViewSet):
queryset = Prefix.objects.all()
queryset = Prefix.objects.prefetch_related("scope")
serializer_class = serializers.PrefixSerializer
filterset_class = filtersets.PrefixFilterSet

Expand All @@ -100,7 +103,17 @@ class IPRangeViewSet(NetBoxModelViewSet):


class IPAddressViewSet(NetBoxModelViewSet):
queryset = IPAddress.objects.all()
queryset = IPAddress.objects.prefetch_related(
GenericPrefetch(
"assigned_object",
[
# serializers are taken according to IPADDRESS_ASSIGNMENT_MODELS
FHRPGroup.objects.all(),
Interface.objects.select_related("cable", "device"),
VMInterface.objects.select_related("virtual_machine"),
],
),
)
serializer_class = serializers.IPAddressSerializer
filterset_class = filtersets.IPAddressFilterSet

Expand Down