基于本教程:
from mongoengine import *
connect('tumblelog')
class User(Document):
email = StringField(required=True, unique=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, reverse_delete_rule=CASCADE)
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()
def main():
john = User(email='jdoe@example.com', first_name='John', last_name='Doe')
john.save()
john_from_db = User.objects(email='jdoe@example.com')
post1 = TextPost(title='Fun with MongoEngine', author = john_from_db)
post1.content = 'Took a look at MongoEngine today, looks pretty cool.'
post1.tags = ['mongodb','mongoengine']
post1.save()
if __name__ == '__main__':
main()
我在 post1.save() 上收到此错误:
mongoengine.base.ValidationError: ValidationError(A ReferenceField only accepts DBRef or documents: ['author'])
我尝试在 ReferenceField 声明中添加 dbref=True/False 选项,但它没有解决任何问题。对象 john 是 User 类型,而 john_from_db 是 QuerySet。当然我在这里遗漏了一些东西,你如何从数据库中获取一个对象并在另一个中使用它?