I am using pymongo and trying to find the best way to construct classes. Currently, I am doing something like this:
class AssetCollection:
def __init__(self,db,**kwargs):
self.__dict__.update(kwargs)
self.Device = Device(db,**db.Devices.find_one({'_id':kwargs['DeviceID']}))
def __repr__(self):
return '<%s %s>' % (self.Name,self._id)
This is extremely flexible, mimicking the flexibility of MongoDB, however I’m not sure its the best way. For example, a problem that could present itself is that the object fail to instantiate if the Device lookup returns None. I should be able to avoid that by ensuring deletes cascade properly within the db, but should I be handling that within the class as well? Any other pitfalls?
Any advice is greatly appreciated.
Do neithe mongokit or mongoengine work for you?
If assetcollection requires a non None Device then yes you need to check it. You could easily raise an errorif find_one returns none.
What is AssetCollection? it doesnt appear assetcollection is even a collection but is instead just a Device?