直接在Django中使用pymongo

编程入门 行业动态 更新时间:2024-10-14 08:30:26
本文介绍了直接在Django中使用pymongo的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用Django和MongoDB建立一个网站.我们可以使用两种流行的API框架来连接Django和MongoDB,一个是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直接连接Django和MongoDB.

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

本文发布于:2023-11-14 20:11:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1588409.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Django   pymongo

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!