【问题标题】:Django not accepting parsed csv date input even though it follows the YYYY-MM-DD format. What is the problem?Django 不接受解析的 csv 日期输入,即使它遵循 YYYY-MM-DD 格式。问题是什么?
【发布时间】:2021-08-01 23:12:27
【问题描述】:

我正在尝试使用 csv 文件中的值填充我现有的 Django 模型。我尝试过使用 datetime.strptime() 但它也没有奏效。

这是我试图从 Django python manage.py shell 运行的代码 加载csv.py

import csv
from dashboard.models import Checkin
with open('foo.csv') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')

    for row in csv_reader:
        new_checkin = Checkin(date=row[0],project_id=row[1],manager_id=row[2],user_id=row[3],hours=row[4])
        new_checkin.save()
        # # row[0] = date;
        # # row[1] = project
        # # row[2] = manager
        # # row[3] = user
        # # row[4] = hours
        

models.py (dashboard.models)

from django.db import models

# Create your models here.
class Checkin(models.Model):
    date = models.DateField(blank=False)
    project_id = models.IntegerField(blank=False)
    manager_id = models.IntegerField(blank=False)
    user_id = models.IntegerField(blank=False)
    hours = models.DecimalField(max_digits=5, decimal_places=2)
    

foo.csv 示例条目

date,project_id,manager_id,user_id,hours
2019-09-11,134,1,1,3
2019-09-11,201,1,1,5
2019-12-23,14,8,2,0.46
2019-12-23,14,8,2,0.46

我遇到的错误

django.core.exceptions.ValidationError: ['“date” value has an invalid date format. It must be in YYYY-MM-DD format.']

当我在 shell 中手动创建单个对象时,我可以保存到数据库中,如下所示:

from dashboard.models import Checkin

new_checkin = Checkin(date="2012-01-01", manager_id="5", project_id="5",user_id="3", hours="0.75")
new_checkin.save()

【问题讨论】:

    标签: python django csv


    【解决方案1】:

    阅读 csv 时需要跳过标题。 Django 抱怨标题“日期”不是日期格式。 您可以使用 next 或 DictReader 来跳过标题。

    【讨论】:

    • 谢谢,在 for 循环之前用“next(csv_reader)”修复它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-20
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 2016-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多