数据未使用 django import export 在 mysqldb 中导入

data isn't importing in mysqldb using django import export

我是 Django 的新手。我正在尝试使用 Django 导入导出将 excel sheet 导入 MySQL dB table。我遵循了导入文档。在尝试测试数据导入时出现错误。

以下是我的观点:

from django.shortcuts import render
from pathlib import Path
import os
from .resources import ProductsResource
from tablib import Dataset



def home(requests):
    dataimport()
    return render(requests,'dbapp/index.html')

def dataimport():

        products_resource = ProductsResource()
        dataset = Dataset()

        dirname = Path(__file__).resolve().parent.parent
        file_name = 'Price.xlsx'
        file_location = os.path.join(dirname, file_name)
        df = pd.read_excel(file_location, header=1, usecols='A:F')
        
        dataset.load(df)
        result = product_resource.import_data(dataset, dry_run=True, raise_errors=True) # Test the data import
        print(result.has_errors())
        if not result.has_errors():
           products_resource.import_data(dataset, dry_run=False)  # Actually import now

Resource.py:

from import_export import resources
from .models import  Products

class ProductsResource(resources.ModelResource):
    class Meta:
        model = Products

Models.py:

from django.db import models
from django.db.models.fields import DateField

class Products(models.Model):
    date = models.DateField(auto_now_add=False,auto_now=False)
    salt = models.FloatField()
    oil = models.FloatField()
    honey = models.FloatField()
    butter = models.FloatField()
    milk = models.FloatField()

我的 excel 文件如下所示:

    Date    Salt    Oil     Honey   Butter  Milk
2020-1-1    26.5    106.5   281     387.5   83
2020-1-2    26.2    106.2   279.8   386     82.4
2020-1-3    26      106     279     385     82
2020-1-4    25      105     275     380     80
2020-1-5    26.2    106.2   279.8   386     82.4
2020-1-6    26.1    106.1   279.4   385.5   82.2

错误信息:

IntegrityError at /
(1048, "Column 'date' cannot be null")
Request Method: GET
Request URL:    http://127.0.0.1:8000/
Django Version: 3.1.7
Exception Type: IntegrityError
Exception Value:    
(1048, "Column 'date' cannot be null")
Exception Location: C:\Users\shash\.virtualenvs\DBProjectWorkspace-IwiT3tz3\lib\site-packages\django\db\backends\mysql\base.py, line 78, in execute
Python Executable:  C:\Users\shash\.virtualenvs\DBProjectWorkspace-IwiT3tz3\Scripts\python.exe
Python Version: 3.9.2

请您再次 运行 并 raise_errors=True 并 post 返回错误消息。您可以按如下方式更改您的代码。

result = products_resource.import_data(dataset, dry_run=True, raise_errors=True)

您可以编辑现有问题以包含错误消息,而不是回复新的 post。

我的猜测是您的 csv 中的字段名称与模型字段名称不匹配,然后当无法使用空值创建记录时会引发错误。

如果是这种情况,那么您可以更改 csv header 名称,以便它们与模型字段名称相匹配:Salt 变为 salt,或者在中声明每个字段ModelResource 以便列和 csv 字段匹配,例如

name = Field(attribute="salt", column_name="Salt")

不过,这只是猜测,可能还有其他问题。

如果您是 Django 的新手,那么我强烈建议您使用 IDE,例如 PyCharm,然后设置调试器。这意味着您可以逐行执行程序,并准确了解问题所在。通过这样做你可以学到很多东西,而且比在 SO 上提问要快得多。

此外,我建议在 singular form rather than plural 中命名您的 Django 模型,因此 Product 而不是 Products