From 3e6b64c7f0065fa6f5a68b81b487fd3b619ec7c1 Mon Sep 17 00:00:00 2001 From: Struan Donald Date: Thu, 6 Feb 2025 14:36:18 +0000 Subject: [PATCH] [CAPE] make link_combined_authorities more robust if CA missing Rather than falling over spit out an error message indicating which authority is missing to make it easier to fix Related to #719 --- .../commands/link_combined_authorities.py | 47 ++++++++++++------- 1 file changed, 29 insertions(+), 18 deletions(-) diff --git a/caps/management/commands/link_combined_authorities.py b/caps/management/commands/link_combined_authorities.py index 96c806cb..63bd92bd 100644 --- a/caps/management/commands/link_combined_authorities.py +++ b/caps/management/commands/link_combined_authorities.py @@ -1,28 +1,39 @@ -from caps.models import Council from django.core.management.base import BaseCommand, CommandError from caps.import_utils import get_council_df - - -def link_combined_authorities(): - df = get_council_df() - - # limit just to those that have 'combined-authority' - df = df[~df["combined-authority"].isna()] - - # iterate and link - for _, row in df.iterrows(): - council = Council.objects.get(authority_code=row["local-authority-code"]) - combined_authority = Council.objects.get( - authority_code=row["combined-authority"] - ) - council.combined_authority = combined_authority - council.save() +from caps.models import Council class Command(BaseCommand): help = "Adds authority codes to the csv of plans" + def link_combined_authorities(self): + df = get_council_df() + + # limit just to those that have 'combined-authority' + df = df[~df["combined-authority"].isna()] + + # iterate and link + for _, row in df.iterrows(): + try: + council = Council.objects.get( + authority_code=row["local-authority-code"] + ) + except Council.DoesNotExist: + self.stderr.write(f"Can't find council {row['nice-name']}") + try: + combined_authority = Council.objects.get( + authority_code=row["combined-authority"] + ) + except Council.DoesNotExist: + self.stderr.write( + f"Can't find combined authority {row['combined-authority']} for {row['nice-name']}" + ) + continue + + council.combined_authority = combined_authority + council.save() + def handle(self, *args, **options): print("linking combined authorities") - link_combined_authorities() + self.link_combined_authorities()