如何使用Django将数据导入数据库

时间:2019-02-11 10:24:13

标签: django database

我正在尝试使用Django将数据从excel工作表导入数据库,但无法正常工作。

excel文件由2列标题组成。

id -
name
  

错误行号:1-'id'无,测试回溯(最近的呼叫)   最后):文件   “ C:\ Users \ LTGM〜1 \ Desktop \ TESTFO〜1 \ testanal \ lib \ site-packages \ import_export \ resources.py”,   第492行,在import_row实例中,new =   self.get_or_init_instance(instance_loader,row)文件   “ C:\ Users \ LTGM〜1 \ Desktop \ TESTFO〜1 \ testanal \ lib \ site-packages \ import_export \ resources.py”,   第269行,在get_or_init_instance实例=   self.get_instance(instance_loader,row)文件   “ C:\ Users \ LTGM〜1 \ Desktop \ TESTFO〜1 \ testanal \ lib \ site-packages \ import_export \ resources.py”,   第263行,在get_instance中返回instance_loader.get_instance(row)   文件   “ C:\ Users \ LTGM〜1 \ Desktop \ TESTFO〜1 \ testanal \ lib \ site-packages \ import_export \ instance_loaders.py”,   第31行,在get_instance字段= self.resource.fields [key] KeyError中:   'id'

我尝试了import_export模块。

  1. 在models.py中创建类
  2. 在resources.py中创建资源
  3. 在admin.py中创建管理员
  4. 在views.py中创建函数

models.py

from django.db import models

# Create your models here.
class criminal_type(models.Model):
    criminal_typeID = models.AutoField(primary_key=True)
    name = models.CharField(max_length=10)

    def __str__(self):
        return str(self.name)

resources.py

from import_export import resources
from .models import criminal_type
# from .models import Mouhafazat


class criminal_type_resource(resources.ModelResource):
    class Meta:
        model = criminal_type

admin.py

from import_export.admin import ImportExportModelAdmin
from django.contrib import admin
from .models import criminal_type

@admin.register(criminal_type)
class CriminalTypeAdmin(ImportExportModelAdmin):
    pass

views.py

from django.shortcuts import render
from tablib import Dataset


# Create your views here.

def simple_uploadCriminalType(request):
    if request.method == 'POST':
        criminalType = criminal_type_resource()
        dataset = Dataset()
        newCriminalType = request.FILES['myfile']

        imported_data = dataset.load(newCriminalType.read(),format="xlsx")
        result = criminalType.import_data(dataset, dry_run=True)  # Test the data import

        if not result.has_errors():
            criminalType.import_data(dataset, dry_run=False)  # Actually import now

    return render(request, 'core/simple_upload.html')

0 个答案:

没有答案