I am writing a function to read xlsx and write this data to the database with Django. But I have so many fields that I cannot define statically. I want to write these fields to the database with a certain algorithm. When designing this, I get the class attributes with _meta.get_fields(). But as seen in this example, attributes always remain None. In views.py there is an example between BEGIN and END codes. How can i solve this problem?
views.py
# ... some codes ...
@login_required(login_url='/admin/login/')
def import_process(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
file_in_memory = request.FILES['file'].read()
wb = load_workbook(filename=BytesIO(file_in_memory), data_only=True)
ws = wb.worksheets[0]
ws_company_name = str(ws["D9"].value)
ws_company_address = str(ws["D10"].value)
# ... some codes ...
# Company Tower Get ID loop
company_staff = CompanyStaff.objects.filter(company_id=Company.objects.filter(company_name=ws_company_name)[0].id)[0]
for col in COLUMN_PARAMETER_LIST:
column_cell = str(col) str(COLUMN_PARAMETER_BEGIN)
ws_tower_type = str(ws[column_cell].value)
tower_type = TowerType.objects.filter(tower_type=ws_tower_type)[0]
c_tower_object = CompanyTower.objects.filter(company_staff_id=company_staff,tower_type_id=tower_type)[0]
tower_data = TowerData.objects.create(company_tower_id=c_tower_object)
ROW_IDX = int(ROW_PARAMETER_BEGIN-1)
# ****************** BEGIN ****************** #
site_fields = tower_data._meta.get_fields()
site_fields_names = [f.name for f in site_fields][1:]
for mfield in site_fields_names:
if any(word in str(mfield) for word in TOWER_DATA_EXCLUDE_FIELDS_NEW):
continue
else:
ROW_IDX = 1
tower_data_cell = str(col) str(ROW_IDX)
tower_data_cell_value = ws[tower_data_cell].value
tower_data.mfield = tower_data_cell_value
if str(mfield) == 'ph': # Example Field
print(tower_data.mfield)
print(tower_data.ph)
# ******************* END ******************* #
tower_data.save()
print("****************")
return render(request, template_name='import.html',context={"form": UploadFileForm()})
# ... some codes ...
CodePudding user response:
You're currently setting and replacing an attribute called mfield
over and over: tower_data.mfield = tower_data_cell_value
.
What you want is setattr(tower_data, mfield, tower_data_cell_value)