60 lines
1.9 KiB
Python
60 lines
1.9 KiB
Python
import csv
|
|
|
|
from django.core.management.base import BaseCommand
|
|
|
|
from main.models import MonthlyTrip
|
|
|
|
|
|
class Command(BaseCommand):
|
|
help = "Import fuel purchases from a CSV file"
|
|
|
|
def add_arguments(self, parser):
|
|
parser.add_argument('csv_file', type=str, help='Path to the CSV file')
|
|
|
|
def handle(self, *args, **kwargs):
|
|
csv_file = kwargs['csv_file']
|
|
|
|
MONTH_MAP = {
|
|
'Tammikuu': 1,
|
|
'Helmikuu': 2,
|
|
'Maaliskuu': 3,
|
|
'Huhtikuu': 4,
|
|
'Toukokuu': 5,
|
|
'Kesäkuu': 6,
|
|
'Heinäkuu': 7,
|
|
'Elokuu': 8,
|
|
'Syyskuu': 9,
|
|
'Lokakuu': 10,
|
|
'Marraskuu': 11,
|
|
'Joulukuu': 12,
|
|
}
|
|
|
|
with open(csv_file, newline='', encoding='utf-8') as f:
|
|
reader = csv.reader(f, delimiter=';')
|
|
headers = next(reader)
|
|
|
|
for line_number, row in enumerate(reader, start=2):
|
|
if len(row) < 3:
|
|
self.stdout.write(self.style.WARNING(f"Skipped broken row {line_number}: {row}"))
|
|
continue
|
|
|
|
try:
|
|
year_str, month_name, value_str = row
|
|
|
|
year = int(year_str.strip())
|
|
month = MONTH_MAP.get(month_name.strip())
|
|
value = int(value_str.strip())
|
|
|
|
MonthlyTrip.objects.update_or_create(
|
|
year=year,
|
|
month=month,
|
|
kilometers=value,
|
|
)
|
|
|
|
self.stdout.write(self.style.SUCCESS(f"Imported: {year} {month} {value}"))
|
|
|
|
except Exception as e:
|
|
self.stdout.write(self.style.ERROR(f"Error on row {line_number}: {row}"))
|
|
self.stdout.write(self.style.ERROR(str(e)))
|
|
|
|
self.stdout.write(self.style.SUCCESS("All imported successfully!"))
|