Django用mongoengine操作mongodb

时间:2021-08-02 05:07:44

 最近在写Django项目,使用的是mongodb,虽然Django不支持NoSQL,但是mongoengine可以帮助我们像ORM一样在Django项目中去操作mongodb

推荐一个可视化工具  Robo 3T 

这里贴几个我觉得比较有帮助的帖子,特别是在一对一,一对多的引用

先放mongoengine的官方文档

http://docs.mongoengine.org/tutorial.html

这是翻译的中文文档,版本比较老,对应官方文档看
https://www.cnblogs.com/fillim/p/4864523.html

https://blog.csdn.net/qq_38890497/article/details/80392846

https://www.linuxzen.com/mongoengineshi-yong-bi-ji.html

1. 首先修改settings.py, 原来DATABASES完全不用去管它了, 全部设为空串就好, 然后在文件里加上下面的内容

如有必要可在INSTALLED_APPS中注册一下

#settings.py

from mongoengine import connect  
connect(DB_NAME)  

#####ReferenceField 引用字段

class Org(Document):
    owner = ReferenceField(User)
 
class User(Document):
    org = ReferenceField(Org, reverse_delete_rule=CASCADE)
 
User.register_delete_rule(Org, owner, DENY)

2.创建集合 

# model.py
 
from mongoengine import *
from datetime import datetime,timedeltaclass User(Document):
    name = StringField(max_length=32)
   age = IntField() password = StringField(max_length=32

引用查询

from mongoengine import *
from datetime import datetime,timedelta
from ReferencenField import *
import json
from bson import json_util
 
connect(mongotest)
 
# 一对一引用查询
author = User.objects.filter(name="John Smith")[0]
author2 = Page.objects.filter(content="test3 Page").first().author
 
content = Page.objects.filter(author=a)
content_ = Page.objects(author__in=[a])
 
print(author.name)
print(author2.name)
 
print(content_)
 
for i in content:
    print(i.author.name,:,i.content)
 
# 一对多引用查询
John_Smith = User.objects.filter(name="John Smith")[0]
llz = User.objects.filter(name=lilinze)[0]
# print(llz.name)
 
print(查询作者是llz的Page)
pages = Page.objects.filter(author=llz)
for i in pages :
    print(i.content)
 
print(查询作者是John_Smith的Page)
pages = Page.objects.filter(author=John_Smith)
for i in pages:
    print(i.content)

嵌入

from mongoengine import *
from datetime import datetime,timedelta
from bson.objectid import ObjectId
 
connect(mongotest)
 
class User(Document):
    name = StringField()
    pages= StringField()
    time = DateTimeField()
    
class Tags(EmbeddedDocument):
    name = StringField()
    date = DateTimeField(default=datetime.now())
 
class Page(Document):
    content = StringField()
    quadrant =StringField()
    #两种嵌入写法
    # tags = ListField(EmbeddedDocumentField(‘Tags‘))
    tags = EmbeddedDocumentListField(Tags)
    author = ReferenceField(User,reverse_delete_rule = CASCADE)
 
user = User.objects.get(name=llz)
tag = Tags(name=123)
tag1 = Tags(name=456)
page = Page(content=嵌入1,quadrant=北面,tags=[tag,tag1],author=user)
page.save()

Objectid转为字符串

John = User.objects.filter(name="John Smith")[0].id
print(John)
dict = {John:John}
print(dict:,dict)
# j_son = json.dumps(dict)
 
print(--------ObjectId转为Json----------)
data = json_util.dumps(John)
print(data:,data)
print(type:,type(data))
 
 
print(--------Json--to--dict----------)
print(********************************)
dd = json.loads(data)
print(dd)
print(type(dd))
print(dd[$oid])
print(type(dd[$oid]))
dd_ = {$oid:dd[$oid]}
jdd_ = json.dumps(dd_)
objecdd_ = json_util.loads(jdd_)
print(objecdd_)
print(type(objecdd_))
print(********************************)
 
print(--------Json--to--ObjectId----------)
ObjectId = json_util.loads(data)
print(ObjectId)
print(type(ObjectId))

字符串转objectID

from bson.objectid import ObjectId
 
 
a = 5bfe034c07aae823b440fdcf
 
# 判断是否符合object格式
 
if ObjectId.is_valid(a):
 
    A = ObjectId(a)     
 
    print(A)                  
                                    # <class ‘bson.objectid.ObjectId‘>,id是bson
 
    print(isinstance(A,ObjectId))   # True

create() ,存入一个新对象,并返回

llzid = User.objects.create(name=zzz)
print(llzid.name)
 
>>>zzz