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...