2

I'm using Python 3.6.2 with Flask and PyMongo and I'm currently saving my data (example: Admin-Object) to MongoDB as follows:

Admin Class:

class Admin(object):
    def __init__(self, email, password, _id=None):

        self._id = uuid.uuid4().hex if _id is None else _id
        self.email = email
        self.password = password

Saving to MongoDB in admin.py:

def save_to_db(self):
    database.Database.insert(collection="admins", data=Utils.to_json(self))

Utils.to_json function:

@staticmethod def to_json(object):
    json_string = json.dumps(object, default=lambda o: o.__dict__)
    json_dict = json.loads(json_string)
    return json_dict

This works like a charm and keeps my code short so I don't have to write json() functions for each class. Also, I started using this method so that I can save nested objects to MongoDB and this is the best way I found so far to do this.

Now the only problem is that I cannot save datetime objects to MongoDB. When I try the following I get the following error message:

Admin Class (NEW):

class Admin(object):
    def __init__(self, email, password, created_at=None, _id=None):

        self._id = uuid.uuid4().hex if _id is None else _id
        self.email = email
        self.password = password
        self.created_at = datetime.datetime.utcnow() if created_at is None else created_at

File "/.../utils.py", line 15, in json_string = json.dumps(object, default=lambda o: o.__ dict __ ) AttributeError: 'datetime.datetime' object has no attribute '__ dict __'

I tried it the following way, by saving it as a string, but then I realized that I need to save it in datetime format so I can query for it in MongoDB.

How to save it to MongoDB in Datetime format? Since MongoDB supports this format there should be a way, no?

PS: Please keep in mind that I need to be able to save complex nested objects which can also contain datetime objects. So building my own json-function seems not the way to go here either...

Pascal
  • 1,661
  • 17
  • 29
  • have you tried using bson [dumps](http://api.mongodb.com/python/current/api/bson/json_util.html#bson.json_util.dumps) and [loads](http://api.mongodb.com/python/current/api/bson/json_util.html#bson.json_util.loads) ? – s7vr Oct 10 '17 at 20:24
  • I tried, but getting the same `datetime.datetime' object has no attribute '__dict__'"`.. – Pascal Oct 10 '17 at 21:14
  • I was expecting it to work and serialize as `created_at :{“$date”: millisecondsvalue}`. Not sure what is going on. May be you can try `from bson import json_util from bson.json_util import STRICT_JSON_OPTIONS json_util.dumps(object, json_options=STRICT_JSON_OPTIONS))`. I'll let others help you. – s7vr Oct 10 '17 at 21:30
  • Your `default=lambda o: o.__dict__` handler can't handle datetime, no. You'll have to come up with a replacement function that handles datetime objects too. I've duped this to the canonical JSON-and-datetime post. – Martijn Pieters Oct 11 '17 at 07:21

0 Answers0