2

I am using peewee ORM for read data from a MySQL database. My DB model class as below

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())
        ])
.............

I am setting data from ORM in following code

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

I am getting following error for some of data rows which having updated_date fields as '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'

why I am getting this error?

PS: AttributeError: 'str' object has no attribute 'isoformat' does not answers my question

vecasa3140
  • 33
  • 1
  • 4
  • You expect `self.updated_date` to be a `datetime` object, while in fact it is an `str` object. Do peewee docs mention anything about the usage of `DateTimeField`? – DeepSpace Dec 18 '19 at 11:49
  • @DeepSpace it's not, see `updated_date = DateTimeField(default=datetime.datetime.now)` – vecasa3140 Dec 18 '19 at 11:51
  • The error you are getting states very clearly that `self.updated_date` is `str` – DeepSpace Dec 18 '19 at 11:52

1 Answers1

1

Probably the database you are using contains datetimes that are not parse-able or otherwise cannot be handled correctly when reading the data off the cursor. Peewee will automatically try to convert string datetime values into the appropriate python datetime instance, but if you have garbage or weirdly-formatted data in the table it will not work.

This is typically only a problem for sqlite databases, as the other dbs will enforce a valid datetime being stored in a datetime-affinity column.

You can try to work around it by extending the supported formats of the relevant fields. e.g., DateTimeField has a list of formats it will automatically parse (field.formats). You can extend this to include whatever format you are using.

coleifer
  • 24,887
  • 6
  • 60
  • 75
  • Thank you, as you mentioned update_date filed had some values like ''0000-00-00 00:00:00'' and I've noticed that supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59' in Mysql Documentation. I've removed them and now it works fine – vecasa3140 Dec 19 '19 at 11:54