直接在Django中使用pymongo [英] Use pymongo in django directly

查看:789
本文介绍了直接在Django中使用pymongo的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Django和MongoDB建立一个网站.我们可以使用两种流行的API框架来连接DjangoMongoDB,一个是mongoengine,另一个是django-mongodb-engine.

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.

因为不再支持最新的mongoengine Django 文档,并且django-mongodb-engine需要另一个django-nonrel软件包,它使开发环境有些复杂.

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.

我想知道是否可以使用Pymongo直接连接DjangoMongoDB.

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

有没有可以分享相同经验的人?以及如何在Django的setting.py中设置数据库以公开该数据库?

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?

推荐答案

您可以像下面的代码一样使用pyMongo

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)

这篇关于直接在Django中使用pymongo的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆