基于此tutorial:
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。当然我在这里遗漏了一些东西,你如何从数据库中获取一个对象并在另一个中使用它?
答案 0 :(得分:1)
您必须在QuerySet上调用first()以获取与查询匹配的第一条记录,例如
john_from_db = User.objects(email='jdoe@example.com').first()