From 91f40a58e838d7401551a2f966bfa4ddd79e3e57 Mon Sep 17 00:00:00 2001 From: Brian Candler Date: Tue, 30 Jan 2024 12:32:14 +0000 Subject: [PATCH] add_device_type_components.py: update the cached component counts on the Device --- scripts/add_device_type_components.py | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/scripts/add_device_type_components.py b/scripts/add_device_type_components.py index ccb3419..585d5b3 100644 --- a/scripts/add_device_type_components.py +++ b/scripts/add_device_type_components.py @@ -7,12 +7,14 @@ PowerOutlet, Interface, RearPort, FrontPort, DeviceBay, ModuleBay) from extras.scripts import Script, ObjectVar, MultiObjectVar +from django.db.models import F class AddDeviceTypeComponents(Script): class Meta: name = "Add Device Type Components" description = "Add missing components to selected devices" + scheduling_enabled = False manufacturer = ObjectVar( model=Manufacturer, @@ -41,17 +43,17 @@ def run(self, data, commit): # components per the DeviceType definition" # Note that ordering is important: e.g. PowerPort before # PowerOutlet, RearPort before FrontPort - for klass, item, templateitem in [ - (ConsolePort, 'consoleports', 'consoleporttemplates'), + for klass, item, templateitem, counter_name in [ + (ConsolePort, 'consoleports', 'consoleporttemplates', 'console_port_count'), (ConsoleServerPort, 'consoleserverports', - 'consoleserverporttemplates'), - (PowerPort, 'powerports', 'powerporttemplates'), - (PowerOutlet, 'poweroutlets', 'poweroutlettemplates'), - (Interface, 'interfaces', 'interfacetemplates'), - (RearPort, 'rearports', 'rearporttemplates'), - (FrontPort, 'frontports', 'frontporttemplates'), - (DeviceBay, 'devicebays', 'devicebaytemplates'), - (ModuleBay, 'modulebays', 'modulebaytemplates'), + 'consoleserverporttemplates', 'console_server_port_count'), + (PowerPort, 'powerports', 'powerporttemplates', 'power_port_count'), + (PowerOutlet, 'poweroutlets', 'poweroutlettemplates', 'power_outlet_count'), + (Interface, 'interfaces', 'interfacetemplates', 'interface_count'), + (RearPort, 'rearports', 'rearporttemplates', 'rear_port_count'), + (FrontPort, 'frontports', 'frontporttemplates', 'front_port_count'), + (DeviceBay, 'devicebays', 'devicebaytemplates', 'device_bay_count'), + (ModuleBay, 'modulebays', 'modulebaytemplates', 'module_bay_count'), ]: names = {i.name for i in getattr(device, item).all()} templates = getattr(dt, templateitem).all() @@ -64,6 +66,10 @@ def run(self, data, commit): for i in items: i.full_clean() klass.objects.bulk_create(items) + # post_save hook is not called, so we have to update counters ourselves + Device.objects.filter(pk=device.pk).update( + **{counter_name: F(counter_name) + len(items)} + ) self.log_success("%s (%d): created %d %s" % (device.name, device.id, len(items),