数据库中的主管下载

时间:2018-12-06 19:16:29

标签: python django database backend

有以下类型的模型:

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, created = Recipe.objects.get_or_create(par_recipe=ws["B2"].value)

    line, created = Line.objects.get_or_create(par_machine=ws["C2"].value)

    order, created = Order.objects.get_or_create(par_fa=ws["D2"].value)

    data = []
    data_par = []
    _id = 1
    for row in ws.iter_rows(row_offset=1):
        parameter = Parameter()
        parameter.id_parameter = _id
        _id += 1
        parameter.par_rollennr = row[5].value
        parameter.par_definition_id = row[6].value
        parameter.par_name = row[7].value
        data_par.append(parameter)

        measurements = Measurements()
        measurements.par_value = row[8].value
        measurements.line = line
        measurements.order = order
        measurements.parameter = parameter
        measurements.recipe = recipe

        data.append(measurements)
    # Bulk create data
    Measurements.objects.all().delete()
    Parameter.objects.all().delete()
    Parameter.objects.bulk_create(data_par)
    Measurements.objects.bulk_create(data)
    return True

如何避免重复输入参数以及为测量正确分配ID? 如果参数是以下形式的记录:

106 45300 Name
107 45300 Name1
106 45300 Name
108 45301 Name3

0 个答案:

没有答案