有以下型号:
class Parameter (models.Model):
id_parameter = models.IntegerField(primary_key=True)
par_rollennr = models.IntegerField(default=0)
par_definition_id = models.IntegerField(default=0) #not FK
par_name = models.CharField(max_length=200)
class Measurements (models.Model):
id_measurement = models.AutoField(primary_key=True)
par_value = models.IntegerField(default=0)
line = models.ForeignKey(Line, on_delete=models.CASCADE, null=True)
order = models.ForeignKey(Order, on_delete=models.CASCADE, null=True)
recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, null=True)
parameter = models.ForeignKey(Parameter, on_delete=models.CASCADE, null=True)
我写下如下:
def handle_parameters_upload(request, file):
wb = openpyxl.load_workbook(file, read_only=True)
first_sheet = wb.get_sheet_names()[0]
ws = wb.get_sheet_by_name(first_sheet)
recipe, _ = Recipe.objects.get_or_create(par_recipe=ws["B2"].value)
line, _ = Line.objects.get_or_create(par_machine=ws["C2"].value)
order, _ = Order.objects.get_or_create(par_fa=ws["D2"].value)
parameter_data = set()
measurement_data = []
for row in ws.iter_rows(row_offset=1):
parameter_data.add((
row[5].value, row[6].value, row[7].value,
))
# par_rollennr, par_definition_id, par_name, measurement: par_value
measurement_data.append(row[8].value)
# Bulk create data
Measurements.objects.all().delete()
Parameter.objects.all().delete()
parameters = Parameter.objects.bulk_create([
Parameter(
id_parameter=index,
par_rollennr=p_data[0],
par_definition_id=p_data[1],
par_name=p_data[2],
) for index, p_data in enumerate(parameter_data)
])
Measurements.objects.bulk_create([
Measurements(
line=line,
order=order,
recipe=recipe,
par_value=m_data,
parameter=parameter,
)
for parameter, m_data in zip_longest(parameters, measurement_data)
])
return True
因此,我仅根据参数的数量在第一行建立连接。如果我在处理的整个文件中都有重复记录,该如何为所有记录设置parameter_id。