Connect Django Project to MongoDB using Django

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 :

    Now, open settings.py file

  • Step 5 :  Make changes to settings.py file

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

       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

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.