42 lines
1.3 KiB
Python
42 lines
1.3 KiB
Python
|
from openpyxl import load_workbook
|
|||
|
|
|||
|
def get_pk_mapping(object, mapping_key="name"):
|
|||
|
pk_mapping = {}
|
|||
|
for instance in object.objects.all():
|
|||
|
pk_mapping[getattr(instance, mapping_key)] = instance.pk
|
|||
|
|
|||
|
return pk_mapping
|
|||
|
|
|||
|
|
|||
|
def get_col_mappings(sheet, start_col, row_index):
|
|||
|
col_mappings = {}
|
|||
|
for row in sheet.iter_rows(min_col=start_col, min_row=row_index, max_row=row_index, values_only=True):
|
|||
|
for i, col_name in enumerate(row):
|
|||
|
col_mappings[col_name] = i
|
|||
|
|
|||
|
return col_mappings
|
|||
|
|
|||
|
|
|||
|
def get_pk_list_from_str(values_str, pk_mapping, fixes={}):
|
|||
|
pk_list = []
|
|||
|
for value in values_str.split(','):
|
|||
|
processed_value = value.lstrip().rstrip().replace(
|
|||
|
'_', ' ').replace('-', ' ').replace('’', '\'')
|
|||
|
|
|||
|
# Applies any mapping adjustments between spreadsheet data and the database values
|
|||
|
if fixes and processed_value in fixes:
|
|||
|
processed_value = fixes[processed_value]
|
|||
|
|
|||
|
# Adds the pk value for the value in the databse
|
|||
|
if processed_value in pk_mapping:
|
|||
|
pk_list.append(pk_mapping[processed_value])
|
|||
|
|
|||
|
return pk_list
|
|||
|
|
|||
|
|
|||
|
def get_spreadsheet(data_path, spreadsheet_filename):
|
|||
|
spreadsheet_path = data_path / 'resources' / spreadsheet_filename
|
|||
|
workbook = load_workbook(filename=spreadsheet_path)
|
|||
|
return workbook.active
|
|||
|
|