Django批量创建非重复条目

时间:2018-03-03 21:02:48

标签: django excel

我想将Excel文件中的数据插入数据库,但我只想插入非重复的数据。

我编写了此代码,但if语句始终为False

def ca_import(request):
    uploadform=UploadFileForm(None)
    if request.method == 'POST' :
        uploadform = UploadFileForm(request.POST, request.FILES)
        if uploadform.is_valid():
            file = uploadform.cleaned_data['docfile']
            workbook = openpyxl.load_workbook(filename=file, read_only=True)
            # Get name of the first sheet and then open sheet by name
            first_sheet = workbook.get_sheet_names()[0]
            worksheet = workbook.get_sheet_by_name(first_sheet)
            data = []
            try:

               for row in worksheet.iter_rows(row_offset=1): # Offset for header
                  stockname =StocksName()

                  if (StocksName.objects.filter(name=row[0].value).count()<1):  #???
                     stockname.name=row[0].value
                     data.append(stockname)
                     StocksName.objects.bulk_create(data)

               messages.success(request,"Successful" ,extra_tags="saveexcel")
               except :
               messages.error(request,_('Error'),extra_tags="excelerror")

    return render(request, 'BallbearingSite/excelfile.html',{'uploadform':uploadform})

有什么建议可以解决吗?

1 个答案:

答案 0 :(得分:0)

如果您的数据具有唯一ID,则可以使用get_or_create()update_or_create()代替bulk_create()

否则,您必须编写逻辑以检查模型中是否已存在每一行。