Connect Django Project to MongoDB
Last Updated :
15 Mar, 2024
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. Django 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Â
Django 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!
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...