【问题标题】:Django - Saving string field into date field in PostgresDjango - 将字符串字段保存到 Postgres 中的日期字段中
【发布时间】:2021-06-25 11:47:03
【问题描述】:

我正在 Django 中实现一个 Web 应用程序,它允许用户上传 CSVExcel 文件。这些文件有 4 列(将来可能会接受不同数量的列),其中两列是日期。上传文件中的每一行都应该插入到我的 Postgresql 数据库中。

我很难做两件事:

  1. 将上传文件的每一行保存在数据库中。问题源于这两个日期字段是DateTimeField 类型,而上传文件中解析的字段默认为String 类型。

  2. 我也想扩展此例程的功能以处理Excel 文件,但我不知道如何在不探索扩展、从Excel 转换为CSV 等的情况下以优雅的方式完成它. 你有优雅的方法吗?

    def upload_file(request) -> render:
     template = 'my-app/upload.html'
    
     if request.method == 'POST' and request.FILES['csvfile']:
         csv_file = request.FILES['csvfile']
         decoded_file = csv_file.read().decode('utf-8').splitlines()
         csv_reader = DictReader(decoded_file, fieldnames=['col1', 'creation_data', 'last_login_date', 'col2'])
         for user in csv_reader:
             # Create an instance of an User model
             new_user = User()
             # TODO - the fields of dates has to be parsed to datetime!
    
             new_user.__dict__.update(user)
             # Store this user in the database
             new_user.save()
    
     return render(request, template)
    

【问题讨论】:

  • dateutil.parser.parse 是你的朋友。 parse('03/29/2021 8:01') datetime.datetime(2021, 3, 29, 8, 1) 或者你可以走更长的路线并使用datetime.strptime() Strptime

标签: python-3.x postgresql django-models file-upload django-views


【解决方案1】:

如评论中所述,您可以使用 datetime.strptime() 假设您事先知道日期格式(因为如果不知道,这将更加困难,在这种情况下 dateutil 是您的朋友)

对于第二个问题,您可以使用here描述的解决方案

您将需要检查如何获取 excel 包要读取的数据并将其提供给包,因此在使用其中的数据之前您无需保存文件

【讨论】:

    猜你喜欢
    • 2011-12-19
    • 2020-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-01
    • 2018-05-07
    • 1970-01-01
    • 2014-12-11
    相关资源
    最近更新 更多