From 0ee9a65d716d702cd9fc5855e2bc49e1d43a95a3 Mon Sep 17 00:00:00 2001 From: dremerb <9120944+dremerb@users.noreply.github.com> Date: Wed, 29 May 2024 13:59:32 +0200 Subject: [PATCH] Add deletion option to BrokenCableTerminations --- scripts/find_orphaned_cables.py | 30 +++++++++++++++++++++++++----- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/scripts/find_orphaned_cables.py b/scripts/find_orphaned_cables.py index b0e446d..ed4d8b3 100644 --- a/scripts/find_orphaned_cables.py +++ b/scripts/find_orphaned_cables.py @@ -1,23 +1,43 @@ from django.db.models import Count, Q from dcim.models import Cable -from extras.scripts import Script +from extras.scripts import Script, BooleanVar class BrokenCableTerminations(Script): name = f'Find (partially) orphaned cables' description = f'Find cable terminations misising either the A or B termination' + delete_orphans = BooleanVar( + description="Delete orphaned cables (cable missing A and B terminations)" + ) + + delete_partials = BooleanVar( + description="Delete partially orphaned cables (cable either missing A or B termination)" + ) + def run(self, data, commit): cables = Cable.objects.annotate( aterm=Count('terminations', filter=Q(terminations__cable_end="A")), bterm=Count('terminations', filter=Q(terminations__cable_end="B")), - ).filter(Q(bterm=0) | Q(aterm=0) ) + ).filter(Q(bterm=0) | Q(aterm=0)) self.log_info(f'Found {cables.count()} problematic cables in DB') for cable in cables: if cable.aterm == 0 and cable.bterm > 0: - self.log_warning(f'[{cable}](/dcim/cables/{cable.pk}/) is missing \'A\' side termination') + self.log_warning( + f'[{cable}](/dcim/cables/{cable.pk}/) is missing \'A\' side termination' + f'{" => deleting" if data["delete_partials"] else ""}') + if data["delete_partials"]: + cable.delete() elif cable.aterm > 0 and cable.bterm == 0: - self.log_warning(f'[{cable}](/dcim/cables/{cable.pk}/) is missing \'B\' side termination') + self.log_warning( + f'[{cable}](/dcim/cables/{cable.pk}/) is missing \'B\' side termination' + f'{" => deleting" if data["delete_partials"] else ""}') + if data["delete_partials"]: + cable.delete() else: - self.log_warning(f'[{cable}](/dcim/cables/{cable.pk}/) is orphaned') + self.log_warning( + f'[{cable}](/dcim/cables/{cable.pk}/) is orphaned' + f'{" => deleting" if data["delete_orphans"] else ""}') + if data["delete_orphans"]: + cable.delete()