Related Articles

Related Articles

Connect Django Project to MongoDB using Djongo
  • Last Updated : 19 Dec, 2020

Djongo is a SQL to mongodb query transpiler. Using djongo we can use MongoDB as a backend database for our Django project. We don’t even need to change the Django ORM. The best part is that we can setup Django with MongoDB by adding just one line of code. There is no need to change serializers, views, or any other modules.

Official Docs – https://pypi.org/project/djongo/ 

Working – 
Djongo translates a SQL query string into a MongoDB query document. Therefore, there is no need to change models, serializers, views or any Django features. Djongo supports all django contrib libraries which make it an easy to use connector. 

Requirements – 



1. Python 3.6 or higher.

2. MongoDB 3.4 or higher. (If you are using nested queries then MongoDB 3.6 or higher is required.)

Features :  

  • Reuse Django Models/ORM – 
    As Django Models are compatible with Djongo, we can use reuse them.
  • Integrity checks 
    Djongo allows integrity checks like missing values before they are saved to the database.
    For eg- Missing values are never stored if we set null=False, blank=False in EmbeddedField

  • Validators 
    We can apply validation checks like URLValidator, EmailValidator, RegexValidator etc. before each fields are saved to the database.
     

Usage : 

Step 1: Setup Virtual Environment 

virtualenv myenv
myenv\Scripts\activate



Step 2:  Install Django 

pip install django

Step 3: Install Djongo 

pip install djongo

Step 4: Start Django Project 

django-admin startproject geeks_project

Your project structure will look like this :

Step 5:  Make changes to settings.py file 

Now, open settings.py file. Comment out or remove previous SQL Database configuration and add the following code in settings.py file :settings.py

   DATABASES = {
      'default': {
          'ENGINE': 'djongo',
          'NAME': 'your-database-name',
      }
  }

That’s it. Now you can Use Mongodb as a backend database for your django project, without changing a single django model!

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :