python – Connect Mongodb with Django

python – Connect Mongodb with Django

first thank you for your answers and support in this question.

I agree with Sanchit and shreesh katti answers, we can use mongoclient and mongoengine to connect with MongoDB, both works good.

I have found one another way, there is an open source project djongo and I am using djongo to connect with MongoDB database. The main benefit of djongo is that it lets you use everything that django provides ( eg models.Model).

here is link of djongo GitHub page https://github.com/nesdis/djongo

this is settings that we need to use djongo
settings.py

DATABASES = {
default: {
    ENGINE: djongo,
    NAME: MyDB,
}

}

Django works well with Relational databases like PostGreSQL, MySQL. Every django settings needs to have a Database configuration defined with default configurations it also needs database respective engine like psycopg2 for PostGreSQL, mysqlclient for MySQL – if you have multiple database configurations then you need to use database router check here for reference. In case of MongoDB – its a NoSql database which Django officially doesnt support if you really need to use MongoDB create a mongoengine configuration in views and you can define mongo credentials in settings.py

python – Connect Mongodb with Django

Using pymongo in django views:

client = pymongo.MongoClient(MONGO_URI)
mongodb = client[MONGO_DB_NAME]
...
class MongoClassView(View):
   def post(request):
       ...
       mapped_data = {name: John}
       mongodb.get_collection(mycollection).insert(mapped_data)
       return JsonResponse({})

hope this helps

Leave a Reply

Your email address will not be published. Required fields are marked *