How to Connect Django and MongoDB Using Djongo?
To connect Django and MongoDB using Djongo, you can follow these steps:
- Install Djongo package: You can install the Djongo package by running the following command in your terminal or command prompt:
pip install djongo
- Configure the settings.py file: In your Django project, open the
settings.py
file and add the following code to the DATABASES dictionary:
DATABASES = {
'default': {
'ENGINE': 'djongo',
'NAME': 'your-db-name',
}
}
Replace your-db-name
with the name of your MongoDB database.
- Create a model: Create a Django model for your MongoDB collection as you would normally do for a SQL database. Here is an example:
from djongo import models
class Person(models.Model):
name = models.CharField(max_length=50)
age = models.IntegerField()
- Run migrations: Run the following command to apply the migrations:
python manage.py makemigrations
python manage.py migrate
- Use the model: You can now use the model to insert, update, and query data in your MongoDB database:
p = Person(name='John', age=30)
p.save()
persons = Person.objects.all()
for person in persons:
print(person.name, person.age)
That's it! You have successfully connected Django and MongoDB using Djongo.