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:
Name | Description |
minPoolSize/maxPoolSize | Minimum and maximum pool size for connections. |
w | Write concern option. |
wtimeoutMS | Timeout for write concern operations. |
Journal | Journal options. |
readPreference |
Read preference to be used for replica sets. Available options are: primary, primaryPreferred, secondary, secondaryPreferred, nearest. |
maxStalenessSeconds | Specifies, in seconds, how stale (data lagging behind master) a secondary can be before the client stops using it for read operations. |
SSL | Using SSL to connect to the database. |
authSource | Used in conjunction with username, specifies the database associated with the user's credentials. When we use external authentication mechanisms this should be $external for LDAP or Kerberos. |
authMechanism |
|
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.