django默认通过excel和一些字段导入一些字段

时间:2018-01-13 22:00:42

标签: python django excel

我在数据库中导入数据的视图代码如下:

def excel_import(request):
    uploadform=UploadFileForm(None)
    if request.method == 'POST' :
        uploadform = UploadFileForm(request.POST, request.FILES)
        if uploadform.is_valid():
            file = uploadform.cleaned_data['docfile']
            data = bytes()
            for chunk in file.chunks():
                data += chunk
            dataset = XLS().create_dataset(data)
            result = ExportSpec().import_data(dataset,dry_run=False, 
                                              raise_errors=True, 
                                              user=request.user)

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

我的模型是这样的:

class Stocks(models.Model):
    docfile = models.FileField(blank=True,null=True,upload_to='documents/')
    user = models.ForeignKey(User, null=True)
    name = models.CharField(max_length=128,verbose_name=_('stockname'))
    number = models.CharField(max_length=64,verbose_name=_('number'))
    suffix = models.CharField(max_length=12,verbose_name=_('uffix'))
    brand = models.CharField(max_length=64, validators=[
                          RegexValidator(regex='^[A-Z]*$', message=_(u'brand must be in Capital letter'),)], verbose_name=_('brand'))
    comment = models.CharField(blank=True, null=True, 
                             max_length=264, verbose_name=_('comment'))
    price = models.PositiveIntegerField(blank=True, null=True,  
                                      verbose_name=_('price'))
    date = models.DateTimeField(auto_now_add = True,verbose_name=_('date'))

    checking = ((_('pending'),_('pending')),
                (_('reject'),_('reject')),
                (_('approved'),_('approved')),
                (_('expired'),_('expired')),
               )
    confirm = models.CharField(choices=checking,max_length=10, 
                             verbose_name=_('confirmation'), 
                             default=_('pending'))
    seller = models.BooleanField(verbose_name=_('seller'))

我希望通过excel文件获取一些字段,并且默认情况下会设置日期,确认,用户设置等字段 此外,id应默认设置为excel文件的每一行的最新id + 1

感谢任何建议。

1 个答案:

答案 0 :(得分:0)

我在处理Excel文件和openpyxl时通常使用bulk_create来插入带有1个查询的数据库。下面是一个代码示例。

import openpyxl, datetime

file = uploadform.cleaned_data['docfile']
workbook = openpyxl.load_workbook(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 = []

for row in worksheet.iter_rows(row_offset=1): # Offset for header
    stock = Stocks()
    stock.user = request.user
    stock.name = row[0].value
    stock.number = row[1].value
    stock.suffix = row[2].value
    stock.brand = row[3].value
    stock.comment = row[4].value
    stock.price = row[5].value
    stock.date = datetime.datetime.utcnow()
    stock.confirm = 'approved'
    stock.seller = row[6].value
    data.append(stock)

# Bulk create data
Stocks.objects.bulk_create(data)

bulk_create有一些注意事项,因此在使用之前请先阅读文档。