【发布时间】:2021-04-04 08:59:37
【问题描述】:
我是 Django 的新手。我正在尝试使用 Django import-export 将 excel 表导入 MySQL dB 表。我遵循了有关导入的文档。尝试测试数据导入时出错。
以下是我的观点:
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
资源.py:
from import_export import resources
from .models import Products
class ProductsResource(resources.ModelResource):
class Meta:
model = Products
模型.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
【问题讨论】:
标签: django django-import-export