|
| 1 | +import csv |
| 2 | +from datetime import datetime |
| 3 | + |
| 4 | +from django.contrib.gis.geos.error import GEOSException |
| 5 | +from django.core.management.base import BaseCommand |
| 6 | + |
| 7 | +from map.models import RestaurantPermit |
| 8 | + |
| 9 | + |
| 10 | +class Command(BaseCommand): |
| 11 | + help = "Load restaurant permit data from a CSV file" |
| 12 | + |
| 13 | + def add_arguments(self, parser): |
| 14 | + parser.add_argument( |
| 15 | + "csv_file", type=str, help="The path to the CSV file to load" |
| 16 | + ) |
| 17 | + |
| 18 | + def handle(self, *args, **kwargs): |
| 19 | + RestaurantPermit.objects.all().delete() |
| 20 | + |
| 21 | + csv_file = kwargs["csv_file"] |
| 22 | + |
| 23 | + with open(csv_file, "r") as file: |
| 24 | + reader = csv.DictReader(file) |
| 25 | + |
| 26 | + for row in reader: |
| 27 | + has_valid_dates = row["application_start_date"] and row["issue_date"] |
| 28 | + if not has_valid_dates or not row["location"]: |
| 29 | + continue |
| 30 | + |
| 31 | + try: |
| 32 | + restaurant = RestaurantPermit( |
| 33 | + permit_id=row["id"], |
| 34 | + permit_type=row["permit_type"], |
| 35 | + application_start_date=datetime.fromisoformat( |
| 36 | + row["application_start_date"] |
| 37 | + ), |
| 38 | + issue_date=datetime.fromisoformat(row["issue_date"]), |
| 39 | + work_description=row["work_description"], |
| 40 | + street_number=row["street_number"], |
| 41 | + street_direction=row["street_direction"], |
| 42 | + street_name=row["street_name"], |
| 43 | + location=row["location"], |
| 44 | + ) |
| 45 | + restaurant.save() |
| 46 | + |
| 47 | + except GEOSException: |
| 48 | + self.stdout.write( |
| 49 | + f'Invalid location for ID {row["id"]}. Skipping...' |
| 50 | + ) |
0 commit comments