python mongoengine 实例讲解

python mongoengine 实例讲解

mogoengine是实现mogodb的ORM
1 安装

pip install mongoengine

2 连接(以本地连接为例)其中tumblelog是数据库名称

from mongoengine import *

connect('tumblelog')

3 Defining our documents
就像定义数据表一样,我们需要定义每个document的字段

class User(Document):
    email = StringField(required=True)
    first_name = StringField(max_length=50)
    last_name = StringField(max_length=50)

4 定义posts mongodb 允许我们为某个字段存储list类型的值

class Post(Document):
    title = StringField(max_length=120, required=True)
    author = ReferenceField(User)
    tags = ListField(StringField(max_length=30))
    meta = {<!-- -->'allow_inheritance': True}

class TextPost(Post):
    content = StringField()

class ImagePost(Post):
    image_path = StringField()

class LinkPost(Post):
    link_url = StringField()

5 定义comments

一条评论通常与一篇文章相关联。在关系数据库中,要显示带有评论的文章,我们必须从数据库中检索文章,然后再次查询与该文章关联的评论。这是可行的,但是没有真正的理由将评论与相关的文章分开存储,而不是使用关系模型。使用MongoDB,我们可以将注释存储为直接在post文档上嵌入的文档列表。嵌入式文档应该与常规文档一样对待;它只是在数据库中没有自己的集合。使用MongoEngine,我们可以定义嵌入文档的结构,以及实用方法,就像我们对常规文档所做的那样:

class Comment(EmbeddedDocument):
    content = StringField()
    name = StringField(max_length=120)

现在我们可以将comments集合保存到post文档中

class Post(Document):
    title = StringField(max_length=120, required=True)
    author = ReferenceField(User)
    tags = ListField(StringField(max_length=30))
    comments = ListField(EmbeddedDocumentField(Comment))

demo

model.py

from mongoengine import Document,StringField,ReferenceField,ListField,EmbeddedDocument,EmbeddedDocumentField

class User(Document):
    email = StringField(required=True)
    first_name = StringField(max_length=50)
    last_name = StringField(max_length=50)

class Comment(EmbeddedDocument):
    content = StringField()
    name = StringField(max_length=120)

class Post(Document):
    title = StringField(max_length=120, required=True)
    author = ReferenceField(User)
    tags = ListField(StringField(max_length=30))
    comments = ListField(EmbeddedDocumentField(Comment))
    meta = {<!-- -->'allow_inheritance': True}

class TextPost(Post):
    content = StringField()

class ImagePost(Post):
    image_path = StringField()

class LinkPost(Post):
    link_url = StringField()

main.py

from mongoengine import connect
from Entity.model import *
connect("ellis")
ross = User(email='ross@example.com')
ross.first_name = 'Ross'
ross.last_name = 'Lawley'
ross.save()

john = User(email='john@example.com')
john.first_name = 'john'
john.last_name = 'Lawley'
john.save()


post1 = TextPost(title='Fun with MongoEngine', author=john)
post1.content = 'Took a look at MongoEngine today, looks pretty cool.'
post1.tags = ['mongodb', 'mongoengine']
post1.save()


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))

官网
https://docs.mongoengine.org/tutorial.html

posted @ 2020-12-25 14:57  不要摸我的腰  阅读(219)  评论(0编辑  收藏  举报