Bläddra i källkod

Fixes #23743: Create nested inventory items from device type templates (#23824)

* Fixes #23743: Create nested inventory items from device type templates

Creating a device failed when its device type had nested inventory item
templates, because each child looked up its parent item before the
parent had been saved. Inventory items are now created parents first,
with each child assigned the item made from its parent template, so
names repeated under different parents also work.

* Check sibling inventory item names and copy CF defaults per item

Reject duplicate inventory item names under the same parent, including
root items, which the unique constraint does not cover. Fetch custom
field defaults for each item so that items do not share one dict.
bctiemann 23 timmar sedan
förälder
incheckning
6f13d6c926

+ 7 - 2
netbox/dcim/models/device_component_templates.py

@@ -1092,8 +1092,13 @@ class InventoryItemTemplate(LtreeModel, ComponentTemplateModel):
         verbose_name = _('inventory item template')
         verbose_name = _('inventory item template')
         verbose_name_plural = _('inventory item templates')
         verbose_name_plural = _('inventory item templates')
 
 
-    def instantiate(self, **kwargs):
-        parent = InventoryItem.objects.get(name=self.parent.name, **kwargs) if self.parent else None
+    def instantiate(self, parent=None, **kwargs):
+        """
+        Instantiate a new InventoryItem. `parent` is the InventoryItem instantiated from this template's parent.
+        If it is omitted, the parent is looked up by name.
+        """
+        if parent is None and self.parent:
+            parent = InventoryItem.objects.get(name=self.parent.name, **kwargs)
         if self.component:
         if self.component:
             model = self.component.component_model
             model = self.component.component_model
             component_name = self.component.resolve_name(kwargs.get('module'), kwargs.get('device'))
             component_name = self.component.resolve_name(kwargs.get('module'), kwargs.get('device'))

+ 28 - 2
netbox/dcim/models/devices.py

@@ -1128,6 +1128,33 @@ class Device(
                     if hasattr(component, 'module_bay_types'):
                     if hasattr(component, 'module_bay_types'):
                         component.module_bay_types.set(src.module_bay_types.db_manager(using).all())
                         component.module_bay_types.set(src.module_bay_types.db_manager(using).all())
 
 
+    def _instantiate_inventory_items(self):
+        """
+        Instantiate inventory items for the device from its DeviceType's inventory item templates. Templates are
+        processed parents first, and each item is saved before its children are instantiated beneath it.
+        """
+        using = self._state.db
+        # An ltree path sorts after the paths of its ancestors
+        templates = list(self.device_type.inventoryitemtemplates.using(using).order_by('path'))
+
+        # Names need only be unique among siblings. The unique constraint does not cover root templates, as their
+        # parent is NULL, so check for duplicates before creating anything.
+        keys = [(t.parent_id, t.name) for t in templates]
+        if duplicates := {name for parent_id, name in keys if keys.count((parent_id, name)) > 1}:
+            raise AbortRequest(
+                _("Duplicate inventory item names under the same parent: {names}").format(
+                    names=', '.join(sorted(duplicates))
+                )
+            )
+
+        items = {}
+        for template in templates:
+            item = template.instantiate(device=self, parent=items.get(template.parent_id))
+            if cf_defaults := CustomField.objects.get_defaults_for_model(InventoryItem):
+                item.custom_field_data = cf_defaults
+            item.save(using=using)
+            items[template.pk] = item
+
     def save(self, *args, **kwargs):
     def save(self, *args, **kwargs):
         is_new = not bool(self.pk)
         is_new = not bool(self.pk)
 
 
@@ -1165,8 +1192,7 @@ class Device(
             # Disable bulk_create to accommodate MPTT
             # Disable bulk_create to accommodate MPTT
             self._instantiate_components(self.device_type.modulebaytemplates.all(), bulk_create=False)
             self._instantiate_components(self.device_type.modulebaytemplates.all(), bulk_create=False)
             self._instantiate_components(self.device_type.devicebaytemplates.all())
             self._instantiate_components(self.device_type.devicebaytemplates.all())
-            # Disable bulk_create to accommodate MPTT
-            self._instantiate_components(self.device_type.inventoryitemtemplates.all(), bulk_create=False)
+            self._instantiate_inventory_items()
             # Interface parents & bridges have to be set after interface instantiation. Parents are applied first so
             # Interface parents & bridges have to be set after interface instantiation. Parents are applied first so
             # that channel subinterfaces validate against a populated parent.
             # that channel subinterfaces validate against a populated parent.
             update_interface_parents(self, self.device_type.interfacetemplates.all())
             update_interface_parents(self, self.device_type.interfacetemplates.all())

+ 51 - 0
netbox/dcim/tests/test_models.py

@@ -1017,6 +1017,57 @@ class DeviceTestCase(TestCase):
         )
         )
         self.assertEqual(inventoryitem.cf['cf1'], 'foo')
         self.assertEqual(inventoryitem.cf['cf1'], 'foo')
 
 
+    def test_device_creation_nested_inventory_items(self):
+        """
+        Inventory items are instantiated from nested templates beneath the correct parents, including when names
+        repeat under different parents.
+        """
+        device_type = DeviceType.objects.create(
+            manufacturer=Manufacturer.objects.first(),
+            model='Chassis Type',
+            slug='chassis-type'
+        )
+        # The default template ordering lists child templates ahead of their parents
+        for chassis_name in ('Chassis A', 'Chassis B'):
+            chassis = InventoryItemTemplate.objects.create(device_type=device_type, name=chassis_name)
+            psu = InventoryItemTemplate.objects.create(device_type=device_type, name='PSU', parent=chassis)
+            InventoryItemTemplate.objects.create(device_type=device_type, name='Fan', parent=psu)
+
+        device = Device.objects.create(
+            site=Site.objects.first(),
+            device_type=device_type,
+            role=DeviceRole.objects.first(),
+            name='Test Device 1'
+        )
+
+        self.assertEqual(InventoryItem.objects.filter(device=device).count(), 6)
+        for chassis_name in ('Chassis A', 'Chassis B'):
+            chassis = InventoryItem.objects.get(device=device, name=chassis_name, parent__isnull=True)
+            psu = InventoryItem.objects.get(device=device, name='PSU', parent=chassis)
+            fan = InventoryItem.objects.get(device=device, name='Fan', parent=psu)
+            self.assertEqual(fan.cf['cf1'], 'foo')
+
+    def test_device_creation_duplicate_root_inventory_items(self):
+        """
+        Root inventory item templates with the same name abort device creation.
+        """
+        device_type = DeviceType.objects.create(
+            manufacturer=Manufacturer.objects.first(),
+            model='Chassis Type',
+            slug='chassis-type'
+        )
+        # The unique constraint treats NULL parents as distinct, so these can both be saved
+        InventoryItemTemplate.objects.create(device_type=device_type, name='PSU')
+        InventoryItemTemplate.objects.create(device_type=device_type, name='PSU')
+
+        with self.assertRaises(AbortRequest):
+            Device.objects.create(
+                site=Site.objects.first(),
+                device_type=device_type,
+                role=DeviceRole.objects.first(),
+                name='Test Device 1'
+            )
+
     def test_multiple_unnamed_devices(self):
     def test_multiple_unnamed_devices(self):
 
 
         device1 = Device(
         device1 = Device(