How to connect MongoDB database with Django

December 29, 2021

Tags: Technologies
python
Unsplash

 

With Python dominating the preferences among developers in terms of programming languages, it is not surprising that Django, a framework created to work exclusively with this language, is one of the most used this year that ends.

 

Before getting into how we can connect a MongoDB database with Django, let's first give a general definition of these two technologies and how they contribute to the development of an application or web page.

 

What is MongoDB?

 

According to the definition on its official page “MongoDB is a document database, which means that it stores data in documents like JSON. We believe this is the most natural way to think about data and is much more expressive and powerful than the traditional row/column model."

 

The traditional way data is stored and used is structured in a table or row and column format, but this is not the case in real-time. MongoDB stores data in real-time this way using JSON and NoSQL-like documents.

 

What is Django?

 

Again, to define this framework we go to its official page, where they tell us “Django is a high-level Python web framework that encourages rapid development and a clean and pragmatic design. Created by seasoned developers, it takes care of much of the hassle of web development, so you can focus on writing your application without reinventing the wheel. It's free and open-source."

 

How MongoDB connects with Python

 

To connect the MongoDB database with Python, the most popular method is using MongoEngine and here we will explain step by step how to do it:

 

MongoEngine is a document object mapper (like ORM but for document databases) for working with MongoDB from Python.

 

Let's see how to configure MongoEngine and connect to MongoDb using it.

 

Step 1: installation:

 

pip install -u mongoengine

 

Step 2: Requirements:

 

MongoDB 3.4, 3.6, 4.0
pymongo> = 3.4

 

Make sure you have the above requirements installed before continuing with the next steps.

 

Step 3: project / settings.py

 

After starting the Django project, open the settings.py file and add these lines to it. Also, delete or comment out the DATABASES section as shown in the following code snippet.

 

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>
# }
#}

 

No need to migrate and perform migrations because you are using MongoEngine ORM.

 

Also, your models.py file will look like the following code snippet.

 

Step 4: project / models.py

 

from mongoengine import Document, fields
class Blogs(Document):
   name = fields.StringField()
   topic = fields.StringField()
   date = fields.DateTimeField()
   addition_info = fields.DictField()

 

We recommend you on video