django结合mongoengine实现对mongodb的操作(一)
1. 引言
以前一直是使用django+关系型数据库mysql进行开发,现在需要使用django+非关系型数据库mongodb,在django中可以直接运用ORM架构实现对mysql的操作,但是django不支持mongodb,这样我们就需要使用mongoengine这个模块来实现django model的封装
2. 前期准备
- 安装必要的模块mongoengine和pymongo(因为mongoengine依赖pymongo,先安装mongoengine,就会自动安装pymongo)
# 因为直接使用pip安装速度很慢,推荐使用豆瓣镜像
pip install mongoengine -i https://pypi.douban.com/simple
3. 基本连接操作
from mongoengine import *
# 数据库名、ip地址、端口、账号、密码、账号配置数据库、验证方式
connect('project', host='localhost', port=27017, username='xxxx', password='xxxxx', authentication_source='admin', authentication_mechanism='SCRAM-SHA-1')
# 如果mongodb在本地,且不需要身份验证,只填数据库名就可以了
connect('project')
class Post(Document):
title = StringField(max_length=120, required=True)
# 类似外键
author = ReferenceField(User, reverse_delete_rule=CASCADE)
tags = ListField(StringField(max_length=30))
# 继承设置
meta = {'allow_inheritance': True}
# 继承
class TextPost(Post):
content = StringField()
content = StringField()
class ImagePost(Post):
image_path = StringField()
class LinkPost(Post):
link_url = StringField()
# 添加数据
ross = User(email='ross@example.com', first_name='Ross', last_name='Lawley').save()
# 还可以这样添加
ross = User(email='ross@example.com', first_name='Ross', last_name='Lawley').save()
# 还可以这样添加
ross = User(email='ross@example.com')
ross.first_name = 'Ross'
ross.last_name = 'Lawley'
ross.save()
# 获取数据
for post in Post.objects:
print(post.title)
for post in Post.objects:
print(post.title)
# 获取特定的数据内容
for post in Post.objects(tags='mongodb'):
print(post.title)
# 获取特定的数据内容的数量
num_posts = Post.objects(tags='mongodb').count()
print('Found {} posts with tag "mongodb"'.format(num_posts))
4. 支持的字段类型
- BinaryField
- BooleanField
- ComplexDateTimeField
- DateTimeField
- DecimalField
- DictField
- DynamicField
- EmailField
- EmbeddedDocumentField
- EmbeddedDocumentListField
- FileField
- FloatField
- GenericEmbeddedDocumentField
- GenericReferenceField
- GeoPointField
- ImageField
- IntField
- ListField
- MapField
- ObjectIdField
- ReferenceField
- SequenceField
- SortedListField
- StringField
- URLField
- UUIDField
- PointField
- LineStringField
- PolygonField
- MultiPointField
- MultiLineStringField
- MultiPolygonField