How to connect a Django project with MongoDB?
There are three different ways to connect django with mongodb
- MongoEngine: MongoEngine is a Python Object-Document-Mapper. It’s similar to Object-Relational-Mapper in relational databases. MongoEngine has a declarative API that is easy to learn and use.
- Djongo: If you are using a relational database like SQL and want to migrate to MongoDB, for that you can use Djongo. Without changing the Django ORM, Djongo transpiles all the SQL queries to MongoDB syntax queries.
Using PyMongo
PyMongo is a Python distribution containing tools for working with MongoDB. PyMongo is great for writing and saving JSON data to your MongoDB, PyMongo will let you use all of the mongo queries in your python code.
Install pymongo by using the command
pip install pymongo
Create a utils.py file in your project folder and the following code
from pymongo import MongoClient
def get_db_handle(db_name, host, port, username, password):
client = MongoClient(host=host,
port=int(port),
username=username,
password=password
)
db_handle = client[db_name]
return db_handle, client
def get_collection_handle(db_handle, collection_name):
return db_handle[collection_name]
The above methods can be used in views to operate your mongodb.
Using MongoEngine
MongoEngine is an ORM layer on top of PyMongo. So, you still need PyMongo (>=3.4) on your system to use MongoEngine.
Using MongoEngine to connect Django and MongoDB gives you fields like ListField and DictField to handle huge unstructured JSON data.
First, install MongoEngine using:
pip install mongoengine
Add the following code in settings.py of your project folder and remove or comment out DATABASES section
import mongoengine
mongoengine.connect(db=DATABASE_NAME, host=DATABASE_HOST, username=USERNAME, password=PASSWORD)#DATABASES = {
# 'default': {
# 'ENGINE': 'djongo', #'django.db.backends.sqlite3',
# 'NAME': 'blogs', # DB name
# 'USER': 'root', # DB User name <optional>
# }
#}
Add models.py
from mongoengine import Document, fieldsclass Blogs(Document):
name = fields.StringField()
topic = fields.StringField()
date = fields.DateTimeField()
addition_info = fields.DictField()
Note: makemigrations
and migrate
is not needed since you are not using Django ORM here.
Using Djongo
Djongo is an improvement over PyMongo in that developers need not write lengthy queries. It maps Python objects to MongoDB documents, i.e., Object Document Mapping (ODM).
To install Djongo
pip install djongo
Now in the settings.py of your project folder edit the database settings
DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'your-db-name', 'ENFORCE_SCHEMA': False, 'CLIENT': { 'host': 'mongodb+srv://<username>:<password>@<atlas cluster>/<myFirstDatabase>?retryWrites=true&w=majority' } }}
Now run
python manage.py makemigrations <app-name>python manage.py migrate
Next Steps
Now that we know the different ways to connect Django and MongoDB, we have to choose the right one for our project. The approaches have their own pros and cons.
For example, if you are starting from scratch, MongoEngine is a good way to go, as it can easily deal with a lot of unstructured data. If you have a lot of complex queries to write in your application, you should go with PyMongo.
Djongo is more suitable if you have a Django project that needs to migrate to MongoDB from another database, as that would require the least amount of code changes.