morbo.model¶
Models are classes whose instances persist in a MongoDB database. Other than the special validator fields, Models are just regular python classes. You can have whatever non-validator attributes and methods you want. Along with simple persistence, Model subclasses also provide methods for finding, removing and updating instances using almost the same API as pymongo.
- class morbo.model.Model(**kwargs)¶
A class with persistent instances:
class Swallow(Model): is_laden = Bool() speed = TypeOf(float) direction = Enum('N', 'E', 'S', 'W') s = Swallow(is_laden=True, speed=23.7, direction='E') s.save() repr(s._id) # ObjectId('4e7be644d761504a98000000')
- classmethod count()¶
Get a count of the total number of instances of this model.
- classmethod find(spec=None, *args, **kwargs)¶
Find instances of this model. This method is exactly the same as pymongo.Collection.find() except that the returned cursor returns instances of this model instead of dicts:
class Swallow(Model): ... s = Swallow(is_laden=True, speed=23.7, direction='E') s.save() Swallow.find({'direction':'E'}).next() # <Swallow 4e7bea8fd761504ae3000000>
- classmethod find_one(spec_or_id=None, *args, **kwargs)¶
Just like pymongo.Collection.find_one() but returns an instance of this model.
- classmethod get_collection()¶
Get a pymongo.Collection instance for the collection that backs instances of this model:
class Swallow(Model): ... Swallow.get_collection() # Collection(Database(Connection('localhost', 27017), u'morbotests'), u'test')
- classmethod remove(spec=None)¶
Works just like pymongo.Collection.remove(). Note that this is different than the model instance method remove() which removes just that single instance.
- save()¶
Save this instance to the database. Validation is performed first.
- validate()¶
Run validation on all validated fields.
- was_created()¶
Called after the model is saved for the first time.
- was_modified()¶
Called each time the model is saved after the first save.