circuit

3 Ways To Connect Django With MongoDB

Django — MongoDB — Djongo — MongoEngine — PyMongo




Most of the projects stores real-time data which is unstructured so managing NoSql data becomes a headache, and that’s where MongoDB rise and shines. MongoDB lets you manage a large amount of NoSql data easily. But as you might know that Django does not support MongoDB officially.

In this blog, I will show you how easily you can connect Django with MongoDB in different 3 ways.

Connecting Django with MongoDBConnecting Django with MongoDB

1. Djongo

Don’t let the name fool you, this is not miswriting. Djongo is an open-source project and regularly maintained. Djongo will enable us to use all of Django features including Django ORM.

Installation: pip install djongo

Requirements:

  1. Python 3.6 or higher

  2. MongoDB 3.4 or higher

project/Settings.py

DATABASES = {
    **'default'**: {
        **'ENGINE'**: **'djongo'**,           *#'django.db.backends.sqlite3',
        ***'NAME'**: **'blogs'**,              # DB name
        **'USER'**: **'root'**,               # DB User name <optional>
    }
}

After implementing the above settings.py changes run python manage.py makemigrations and then python manage.py migrate

Now, you are ready to go and also you can check more about Djongo here https://github.com/nesdis/djongo

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.

Installation: pip install -u mongoengine

Requirements:

  1. MongoDB 3.4, 3.6, 4.0

  2. pymongo>=3.4

project/Settings.py

Add these lines in settings.py 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>
#    }
#}

Note you do not need to do makemigrations and migrate since you are not using Django ORM here.

Also, your models.py will look something like that

Models.py

**from **mongoengine **import **Document, fields

**class Blogs**(Document):
   name = fields.StringField()
   topic = fields.StringField()
   date = fields.DateTimeField()
   addition_info = fields.DictField()

Now, you are ready to go and also you can check more about MongoEngine here http://docs.mongoengine.org/ and https://github.com/MongoEngine/mongoengine

3. 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.

Installation: pip install pymongo

project/utils.py

create utils.py if project folder and add these lines

**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

views.py

from project.utils import get_db_handle, get_collection_handle

db_handle, mongo_client = get_db_handle(DATABASE_NAME, DATABASE_HOST, DATABASE_PORT, USERNAME, PASSWORD)

collection_handle = get_collection_handle(db_handle, REGIONS_COLLECTION)

collection_hadle.find({...})
collection_handle.insert({...})
collection_handle.update({...})

Note: 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.

Conclusion

Djongo is great and allows us to use Django ORM and most of Django features as it is, But when you are dealing with JSON data you will need your models to have DictField and ListField which is present in MongoEngine but not is Djongo. For example below data is complex and can be handled in MongoEngine easily but not in Djongo.

**from **mongoengine **import **Document, fields

class Blogs(Document):
    blog_detail = field.DictField()
    publications = field.ListField()

# data
{
 "blog_detail":{
      "blog_title": "my_blogs",
      "publish_date": "2020-08-21"
     },
 "publications": ["publisher_1", "publisher_2", "publisher_3"]

}

I personally use MongoEngine to connect with database and for complex queries I use PyMongo. Soon I will write a blog about this and will show you how you can use these in your project.

But for now, if you have any queries please put a comment!




Continue Learning