In this article, you will learn how to connect to a MongoDB database to a Python web application framework Django. You will also learn how to edit your Django Project Settings file and connect your web application to a mongodb (NoSQL or document) Database.
Django is a flexible framework for quickly creating Python applications. By default, Django applications are configured to store data into a lightweight SQLite database file.

Connecting your Django App to a MongoDB database
# Introduction:
Django is used in such an amazing modular style, It’s simple to replace different components of a Django-based web application. Because document(NoSQL) databases are more common these days, you might want to try running an application with a different back end rather than one of the standard relational databases such as MySQL, SQLite, PostgreSQL or etc.
3 Ways To Connect Django With MongoDB:
1.) Djongo
Dongo is an open-source project and regularly maintained.
Djongo is a smarter approach to pymongo programming. It is an extension to the traditional Django ORM framework. It maps python objects to MongoDB documents, a technique popularly referred to as Object Document Mapping or ODM.
# Let's start connecting "Django" with "MongoDB" using djongo
Step 1 : To set up the environment for Djongo, you first need to install the package.
pip install djongo
Step 2 : Now go-to the "settings.py" file of the Django App and Under the settings file for Databases, change the settings from sqlite3 or your current database to the following code.
DATABASES={
'default':{
'ENGINE': 'djongo',
'NAME': 'your-db-name',
'CLIENT': {
'host':'localhost',
'port': 27017,
'username': '',
'password': ''
}
}
}
Step 3 : Now run makemigrations command to convert all the models into queries for the database.
python manage.py makemigrations
Step 4 : And finally run migrate command to migrate these changes into our database.
python manage.py migrate
Note : Congratulations, your Django project is now connected with MongoDB. Have fun!
Requirements
Python 3.6 or higher
MongoDB 3.4 or higher
If your models use nested queries or sub querysets like this:
inner_query = Blog.objects.filter(name__contains='Ch').values('name')
entries = Entry.objects.filter(blog__name__in=inner_query)
Then, MongoDB 3.6 or higher is required.
Note that: Django does't create a MongoDB database. So you must have a pre-made MongoDB database, if not, then you create a new database in Mongodb, Then Djongo helps to connect to that database and acts as a transpiler from SQL to MongoDB.
2.) MongoEngine
MongoEngine is an ORM (object relation mapping) layer on the top of PyMongo written in python. Using MongoEngine will grant you additional benefits like fields DictFieldand ListField which you will see very useful when dealing with unstructured JSON data in MongoDB.
# Let's start connecting "Django" with "MongoDB" using MongoEngine
Step 1 : To set up the environment for Djongo, you first need to install the package.
python -m pip install -U mongoengine
Step 2 : After that, open your project "settings.py", and change the DATABASES part to this code.
# DATABASES={
# 'default':{
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
# }
# }
import mongoengine
mongoengine.connect(db=DATABASE_NAME, db=DATABASE_HOST, db=USERNAME, db=PASSWORD)
Requirements
MongoDB 3.4, 3.6, 4.0
pymongo>=3.4
If your models use nested queries or sub querysets like this:
Note that: You do not need to do makemigrations and migrate since you are not using Django ORM here.
3.) PyMongo
PyMongo is a Python distribution containing tools for working with MongoDB, PyMongo is the recommended way to work with MongoDB from Python. It is great for writing and saving JSON data to your MongoDB, and it will let you use all of the mongo queries in your python code.
Installation
pip install pymongo
# To get a specific version of pymongo:
python -m pip install pymongo==3.5.1
# To upgrade using pip:
python -m pip install --upgrade pymongo
Step 2 : After that Installation, create "utils.py" file in your project root directory(project/utils.py) and add these lines.
➤ Code: utils.py
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]
You can use the above functions in your views or anywhere you want to fetch or write data into your MongoDB.
Note that:
you don’t need anything in models when you are using PyMongo.
Also, no need to add anything in Settings.py but don’t forget to comment out the DATABASES part.
Comments