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

标签 python peewee

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

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]

对于一些更新日期字段为“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 日期时间实例,但如果表中有垃圾或格式奇怪的数据,它将无法工作。

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

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

关于python - 获取 'str' 对象没有 peewee DateTimeField 的属性 'isoformat',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59391371/

相关文章:

python - Peewee - 用字典更新条目

python - 为什么我在 "Unknown column ' 中得到 'where clause' Jacob'?

python - 在 dnspython 中返回 'A' DNS 记录

python :TypeError: this constructor takes no arguments

python - 我的背包代码输出错误?

peewee - 如何在 Peewee 中动态设置 SQLite 数据库文件?

python - TensorArray 和 while_loop 如何在 tensorflow 中协同工作?

python - 如何使用 peewee 在 where 条件后进行连接

python - 如何将新的 ".where()"添加到现有的 peewee 查询中?

database - 皮威 : How to update specific fields?