2

基于本教程

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。当然我在这里遗漏了一些东西,你如何从数据库中获取一个对象并在另一个中使用它?

4

1 回答 1

1

您必须在 QuerySet 上调用 first() 以获取与查询匹配的第一条记录,例如

john_from_db = User.objects(email='jdoe@example.com').first()
于 2013-01-07T00:17:03.170 回答