Use pymongo in django directly

↘锁芯ラ 提交于 2019-11-30 16:38:41

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)

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()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!