2013-01-06 81 views
2

在此基礎上tutorialmongoengine - 使用查詢集爲ReferenceField

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='[email protected]', first_name='John', last_name='Doe') 
    john.save() 
    john_from_db = User.objects(email='[email protected]') 
    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']) 

我嘗試添加了DBREF =真/假的選項ReferenceField聲明,但它沒有解決任何問題。對象john是User類型,而john_from_db是QuerySet。當然,我在這裏錯過了一些東西,你如何從數據庫中獲得一個對象並在另一箇中使用它?

回答

1

您必須調用QuerySet上的first()以獲取與查詢匹配的第一條記錄,例如

john_from_db = User.objects(email='[email protected]').first() 
+0

哦,好吧。謝謝 –