diff --git a/netbox/dcim/models/devices.py b/netbox/dcim/models/devices.py index 64d2e346cf..6c5a2d85d7 100644 --- a/netbox/dcim/models/devices.py +++ b/netbox/dcim/models/devices.py @@ -957,6 +957,11 @@ def _instantiate_components(self, queryset, bulk_create=True): if cf_defaults := CustomField.objects.get_defaults_for_model(model): for component in components: component.custom_field_data = cf_defaults + # Set denormalized references + for component in components: + component._site = self.site + component._location = self.location + component._rack = self.rack components = model.objects.bulk_create(components) # Prefetch related objects to minimize queries needed during post_save prefetch_fields = get_prefetchable_fields(model) diff --git a/netbox/dcim/models/modules.py b/netbox/dcim/models/modules.py index 1c3f9f7307..b5071794a2 100644 --- a/netbox/dcim/models/modules.py +++ b/netbox/dcim/models/modules.py @@ -315,6 +315,12 @@ def save(self, *args, **kwargs): for component in create_instances: component.custom_field_data = cf_defaults + # Set denormalized references + for component in create_instances: + component._site = self.device.site + component._location = self.device.location + component._rack = self.device.rack + if component_model is not ModuleBay: component_model.objects.bulk_create(create_instances) # Emit the post_save signal for each newly created object diff --git a/netbox/dcim/signals.py b/netbox/dcim/signals.py index 9295ddbdba..9079b62781 100644 --- a/netbox/dcim/signals.py +++ b/netbox/dcim/signals.py @@ -44,6 +44,9 @@ def handle_location_site_change(instance, created, **kwargs): Device.objects.filter(location__in=locations).update(site=instance.site) PowerPanel.objects.filter(location__in=locations).update(site=instance.site) CableTermination.objects.filter(_location__in=locations).update(_site=instance.site) + # Update component models for devices in these locations + for model in COMPONENT_MODELS: + model.objects.filter(device__location__in=locations).update(_site=instance.site) @receiver(post_save, sender=Rack) @@ -53,6 +56,12 @@ def handle_rack_site_change(instance, created, **kwargs): """ if not created: Device.objects.filter(rack=instance).update(site=instance.site, location=instance.location) + # Update component models for devices in this rack + for model in COMPONENT_MODELS: + model.objects.filter(device__rack=instance).update( + _site=instance.site, + _location=instance.location, + ) @receiver(post_save, sender=Device)