|
8 | 8 | from django.core.files.storage import default_storage |
9 | 9 | from django.core.validators import MaxValueValidator, MinValueValidator |
10 | 10 | from django.db import models |
11 | | -from django.db.models import F, ProtectedError |
| 11 | +from django.db.models import F, ProtectedError, prefetch_related_objects |
12 | 12 | from django.db.models.functions import Lower |
13 | 13 | from django.db.models.signals import post_save |
14 | 14 | from django.urls import reverse |
|
28 | 28 | from netbox.models.mixins import WeightMixin |
29 | 29 | from netbox.models.features import ContactsMixin, ImageAttachmentsMixin |
30 | 30 | from utilities.fields import ColorField, CounterCacheField |
| 31 | +from utilities.prefetch import get_prefetchable_fields |
31 | 32 | from utilities.tracking import TrackingModelMixin |
32 | 33 | from .device_components import * |
33 | 34 | from .mixins import RenderConfigMixin |
@@ -924,7 +925,10 @@ def _instantiate_components(self, queryset, bulk_create=True): |
924 | 925 | if cf_defaults := CustomField.objects.get_defaults_for_model(model): |
925 | 926 | for component in components: |
926 | 927 | component.custom_field_data = cf_defaults |
927 | | - model.objects.bulk_create(components) |
| 928 | + components = model.objects.bulk_create(components) |
| 929 | + # Prefetch related objects to minimize queries needed during post_save |
| 930 | + prefetch_fields = get_prefetchable_fields(model) |
| 931 | + prefetch_related_objects(components, *prefetch_fields) |
928 | 932 | # Manually send the post_save signal for each of the newly created components |
929 | 933 | for component in components: |
930 | 934 | post_save.send( |
|
0 commit comments