- Mastering MongoDB 3.x
- Alex Giamas
- 145字
- 2021-08-20 10:10:52
PyMODM ODM
Similar to Ruby's Mongoid, PyMODM is an ODM for Python that follows closely on Django's built-in ORM. Installing it can be done via pip:
pip install pymodm
Then we need to edit settings.py and replace the database engine with a dummy database:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.dummy'
}
}
And add our connection string anywhere in settings.py:
from pymodm import connect
connect("mongodb://localhost:27017/myDatabase", alias="MyApplication")
Here we have to use a connection string that has the following structure:
mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
Options have to be pairs of name=value with an & between each pair. Some interesting pairs are:

Model classes need to inherit from MongoModel. A sample class will look like this:
from pymodm import MongoModel, fields
class User(MongoModel):
email = fields.EmailField(primary_key=True)
first_name = fields.CharField()
last_name = fields.CharField()
This has a User class with first_name, last_name, and email fields where email is the primary field.