mongomodels

A simple ODM for MongoDB
Download

mongomodels Ranking & Summary

Advertisement

  • Rating:
  • License:
  • GPL v3
  • Price:
  • FREE
  • Publisher Name:
  • David Litvak
  • Publisher web site:
  • http://github.com/dlitvakb

mongomodels Tags


mongomodels Description

mongomodels is a simple ODM for MongoDB.Installationpip install mongomodelsUsageDefine your base model to refer to the mongo instancefrom mongomodels.db import DocumentDatabasefrom mongomodels.models import ValidatingStructclass BaseModel(ValidatingStruct): __DOCUMENT_DB__ = DocumentDatabase('localhost', 'test_database')Define your modelsEach model must have a document name, so that the it refers to the proper collection on MongoDB. By default it takes the snake_case version of the class.class MyTestModel(BaseModel): # This would map to __DOCUMENT_NAME__ = 'my_test_model' pass # Or you could redefine your document name # __DOCUMENT_NAME__ = 'test_model'Create your objectstest_object = MyTestModel(some_attribute='some value')test_object.save()Find your objectsMyTestModel.all() # Returns a list with all the objects in the documentMyTestModel.all(some_attribute='some value') # Returns all the objects # that meet the same attributesMyTestModel.get() # Returns the first object of the collectionMyTestModel.get(some_attribute='some value') # Returns the first object # that meets the attributesValidations# Let's say we have some Message model that relates to a User and a chat Roomclass Message(BaseModel): # Our previously defined BaseModel def validate(self): self.validate_not_empty('message') self.validate_not_empty('user_id') self.validate_not_empty('room_id') self.validate_existance('user_id', User) self.validate_existance('room_id', Room) self.validate_field( 'message', self.validate_message, 'Message too long, max length is 255' ) def validate_message(self, message): return len(message) return len(message) < = 255For running validations on our models we have to redefine the method validate, in which we will set all our pre save validations.validate_not_empty: Validates that our field has any datavalidate_existance: Validates that the relationship field matches an object on the relationship modelvalidate_field: Validates the given field with a custom function, the function should receive only one argument representing the value to validate and should return a boolean. Also, accepts an optional error message.Product's homepage


mongomodels Related Software