Skip to main content

How to connect MongoDB with Django

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.

how to connect django with mongodb

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.

  2. MongoEngine.

  3. PyMongo.


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
  1. Python 3.6 or higher

  2. MongoDB 3.4 or higher

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

  1. # DATABASES={

  2. #   'default':{

  3. #    'ENGINE': 'django.db.backends.sqlite3',

  4. #    'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),

  5. #   }

  6. # }

  7. import mongoengine

  8. mongoengine.connect(db=DATABASE_NAME, db=DATABASE_HOST, db=USERNAME, db=PASSWORD)

Requirements
  1. MongoDB 3.4, 3.6, 4.0

  2. pymongo>=3.4

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

  1. from pymongo import MongoClient

  2.   

  3. def get_db_handle(db_name, host, port, username, password):

  4.   client = MongoClient(

  5. host=host,

  6. port=int(port),

  7. username=username,

  8. password = password

  9.   )

  10.   db_handle = client[db_name]

  11.   return db_handle, client

  12.   

  13. def get_collection_handle(db_handle, collection_name):

  14.   return db_handle[collection_name]

  15.   

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

Popular Posts

How to remove the date and .html from every blogger post url

#Remove date and .html from blogger post url A Common search term which every blogger search is How to Remove Date From Blogger Post URL or how do I remove date from blogger permalink? Follow the steps below and then date and .html will be removed from the URL of your blogger post. Step 1 : Login to your Blogger blog and select Theme / Template. Step 2 : Click on Edit HTML and paste the below code just above the </head> tag let's see code :   ➤ Code : mycode.js; Copy code <script type='text/javascript' > //<![CDATA[ // BloggerJS v0.3.1 var urlTotal,nextPageToken,postsDatePrefix=!1,accessOnly=!1,useApiV3=!1,apiKey="",blogId="",postsOrPages=["pages","posts"],jsonIndex=1,secondRequest=!0,feedPriority=0,amp="&"[0];function urlVal(){var e=window.location.pathname,t=e.length;return...

Django static files not working when debug false || debug true

# Django static and media files not working when debug is false In this article you will learn how to fix problem of not loading static files and media in Django even the DEBUG is FALSE. This is the easiest and safest solution. # Problem: Django static and media files not working when debug is false  ➤ Code: settings.py DEBUG = False #True ALLOWED_HOSTS = [ '*' ] #Host name # Problem Fix: Let's see, How you can fix the problem of Django static and media files not working when DEBUB = False : 1.)First way: devserver in insecure mode If you still need to server static locally ( e.g. for testing without debug ) you can run devserver in insecure mode: python manage.py runserver --insecure --insecure: it means you can run serve...

Django not able to find static files[Solved]

# Django static files not working In this article, you will learn how to fix the problem of not loading static files. This is the easiest and safest solution. In the new version of Django 3.1 and above the settings.py file uses PATH instead of OS to deal with the directory structure. So all the code, we wrote for our static dirs and things like that will no longer work unless we import os at the top of our settings.py file.. Note : This article related to DEBUG = True , if you have problems with DEBUG = False then you can follow this article; Static files not working when DEGUB= False . Have fun! Let's follow a few steps and, solve the problem of not loading Django static files: Step 1 : Check that "BASE_DIR" is defined in your project settings.py , if not then define it  ➤ Code: settings.py import os BASE_DIR = ...