获取 'str' 对象没有 peewee DateTimeField 的属性 'isoformat'

Getting 'str' object has no attribute 'isoformat' for peewee DateTimeField

我正在使用 peewee ORM 从 MySQL 数据库中读取数据。我的数据库模型 class 如下

import peewee
import datetime
from collections import OrderedDict
...............

class User(peewee.Model):
...............

    created_by = CharField(null=True)
    update_by = CharField(null=True)
    updated_date = DateTimeField(default=datetime.datetime.now)
.................

    def __to_dict__(self):
        user_dict = OrderedDict([
.................
            ('created_by', self.created_by),
            ('update_by', self.update_by),
            ('updated_date', self.updated_date.isoformat())
        ])
.............

我在以下代码中设置来自 ORM 的数据

users= User.select().distinct()
return [user.__to_dict__() for user in users]

对于某些具有 updated_date 字段作为“0000-00-00 00:00:00”的数据行,我收到以下错误

 user = user.__to_dict__()
File "/opt/appserver/app1/app/models/user.py", line 172, in __to_dict__
('updated_date', self.updated_date.isoformat())
AttributeError: 'str' object has no attribute 'isoformat'

为什么我会收到这个错误?

PS: AttributeError: 'str' object has no attribute 'isoformat' 没有回答我的问题

可能您正在使用的数据库包含无法解析的日期时间,或者在从游标读取数据时无法正确处理。 Peewee 会自动尝试将字符串日期时间值转换为适当的 python 日期时间实例,但如果 table 中有垃圾或格式奇怪的数据,它将无法工作。

这通常只是 sqlite 数据库的问题,因为其他数据库会强制将有效的日期时间存储在日期时间关联列中。

您可以尝试通过扩展相关字段的支持格式来解决这个问题。例如,DateTimeField 有一个它将自动解析的格式列表 (field.formats)。您可以扩展它以包括您正在使用的任何格式。