Django model_to_dict skips all DateTimeField when converting models
datetime, django, model
Solution
I found the cause to be auto_now_add=True, it automatically sets editable=False, which causes model_to_dict() to skip the fields
Problem
I just noticed a bug with model_to_dict that it skips all DateTimeField in the model and never convert them to the dictionary, whereas use QuerySet's values() function does not. I looked on the internet but couldn't find anyone else having the same problem. I just want to confirm that this indeed is a problem that other people has encountered and see what people do to solve it. Do everyone just avoid using model_to_dict in this case and tries to emulate the behavior using values()? Or is there a better solution? What are your thoughts? Thanks! Below is the out: ``` >>> member = Member.objects.get(id=1) >>> member.create_time datetime.datetime(2013, 2, 26, 6, 1, 2, tzinfo=<UTC>) >>> model_to_dict(member) {'verified': True, 'name': u'John', 'email': u'', 'phone': u'', 'id': 1L, 'password': u'4e3fc0574fbcdff16c8508339e', 'verify_token': u'5d98aacaba39eb7e'} ``` As you can see 'create_time' field is not in the dictionary. I had to manually insert it: ``` >>> obj = model_to_dict(member) >>> obj {'verified': True, 'name': u'John', 'email': u'', 'phone': u'', 'id': 1L, 'password': u'4e3fc0574fbcdff16c8508339e', 'verify_token': u'5d98aacaba39eb7e'} >>> obj["create_time"] = member.create_time >>> obj {'verified': True, 'name': u'John', 'email': u'', 'phone': u'', 'create_time': datetime.datetime(2013, 2, 26, 6, 1, 2, tzinfo=<UTC>), 'id': 1L, 'password': u'4e3fc0574fbcdff16c8508339e', 'verify_token': u'5d98aacaba39eb7e'} >>> ``` EDIT: I think I found the problem: In model_to_dict(): ``` opts = instance._meta for f in opts.fields: if not f.editable: continue ``` And my create_time field is shown as not editable. Further research indicates that auto_now_add=True will automatically make editable=False. Thus causing model_to_dict() to skip it...