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()
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‘)
ross.first_name = ‘Ross‘
ross.last_name = ‘Lawley‘
ross.save()
# 获取数据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))