Use pymongo in django directly
Asked Answered
C

3

4

I am building a website using Django and MongoDB. There are 2 popular API framework that we can use to connect Django and MongoDB, one is mongoengine and the other is django-mongodb-engine.

Because the latest mongoengine is not supported Django anymore Document, and django-mongodb-engine needs another django-nonrel package which makes the development environment a little bit complicate.

I am wondering, if I could use Pymongo to connect Django and MongoDB directly.

Is there anyone who have the same experience that could share? and how to set the db in setting.py in Django to make the db public?

Cauldron answered 22/7, 2015 at 2:34 Comment(1)
Mongoengine 0.9 can be an option with Django ( given that you do not have dependence on some feature/enhancement in 0.10 release). Read docs for connecting to mongodb.Dyna
C
8

you may use pyMongo like below code

from pymongo import MongoClient


class MongoConnection(object):

    def __init__(self):
        client = MongoClient('localhost', 27017)
        self.db = client['database_name']

    def get_collection(self, name):
        self.collection = self.db[name]

we create a connection as per our need.

class MyCollection(MongoConnection):

    def __init__(self):
       super(MyCollection, self).__init__()
       self.get_collection('collection_name')

    def update_and_save(self, obj):
       if self.collection.find({'id': obj.id}).count():
           self.collection.update({ "id": obj.id},{'id':123,'name':'test'})
       else:
           self.collection.insert_one({'id':123,'name':'test'})

    def remove(self, obj):
        if self.collection.find({'id': obj.id}).count():
           self.collection.delete_one({ "id": obj.id})

Now you just need to call like below.

my_col_obj = MyCollection()
obj = Mymodel.objects.first()
my_col_obj.update_and_save(obj)
my_col_obj.remove(obj)
Crucifix answered 14/12, 2016 at 18:36 Comment(0)
D
2

I am currently working on a very similar problem.

You are right, mongoengine does not support Django, but, as far as I know, pymongo does not support it too. At least mongoengine have plans to support it some day. If you are familiar with Django, it has model-like things - documents. They are easy to work with - this is actually a full working ORM. You don't get that with pymongo and if you are going to build a large, reusable application, you will end up writing ORM yourself or have spaghetti code. This was the reason for me to use mongoengine.

In your settings.py you should include this code:

from mongoengine import connect
connect('your_database')

If you still want to use pymongo for some reason, your code should look like this:

from pymongo import MongoClient
client = MongoClient()
Dermatogen answered 22/7, 2015 at 10:32 Comment(2)
Thank you. If I use the pymongo solution, will the client be the global variable in Django?Cauldron
it is completely up to you to decide - I assume that you are going to use it for some low level stuff and it depends on what you needDermatogen
N
0

Basically it should be possible to create a custom db class with implemented MongoClient() no matter what web framework you chose to work with, Flask, FastAPI, Django. 2nd answer is pretty good example code for this ;)

Nickienicklaus answered 27/3, 2022 at 9:19 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Illaudable

© 2022 - 2024 — McMap. All rights reserved.