2012-08-06 3 views
2

임베디드 문서 클래스가 Post이고 아버지 클래스가 Thread입니다.MongoDB - MongoEngine - 임베디드 문서 저장 기능이 작동하지 않습니다. - 특성 저장이 없습니다.

class Thread(Document): 
    ... 
    posts = ListField(EmbeddedDocumentField("Post")) 

class Post(EmbeddedDocument): 
    attribute = StringField() 
    ... 

나는 새 게시물을 작성하고 Thread 클래스 내 ListField에 추가 할 수 있습니다.

내 코드는 다음과 같습니다

post = Post() 
post.attribute = "noodle" 
post.save() 
thread.posts.append(post) 
thread.save() 

그러나 나는 다음과 같은 오류 메시지가 얻을 :

" '포스트'객체 '저장'에는 속성이 없습니다"

하는 경우를 저는 post.save()을 건너 뛰고 빈 Post 개체가 내 Thread에 추가됩니다.

아이디어가 있으십니까?

+2

이것은 임베디드 시스템 프로그래밍에 관한 것이 아닙니다. 태그가 지정되었습니다. //stackoverflow.com/tags/embedded/info –

답변

3

코드가 정상적으로 보입니다. 다른 스레드 개체가없는 것이 맞습니까? post.save() 단계없이 코드를 증명하는 테스트 사례를 제공합니다. 어떤 버전을 설치하셨습니까?

import unittest 
from mongoengine import * 


class Test(unittest.TestCase): 

    def setUp(self): 
     conn = connect(db='mongoenginetest') 

    def test_something(self): 

     class Thread(Document): 
      posts = ListField(EmbeddedDocumentField("Post")) 

     class Post(EmbeddedDocument): 
      attribute = StringField() 

     Thread.drop_collection() 

     thread = Thread() 
     post = Post() 
     post.attribute = "Hello" 

     thread.posts.append(post) 
     thread.save() 

     thread = Thread.objects.first() 
     self.assertEqual(1, len(thread.posts)) 
     self.assertEqual("Hello", thread.posts[0].attribute) 
+0

감사합니다! 실제로 문제는 tastypie가 데이터의 일부를 "잃어 버렸습니다"라는 것입니다 ... 그래서 전혀 몽고 문제가 없습니다 :) – Ron

+1

* EmbeddedDocumentField (*) 대신 * EmbeddedDocumentField (Post) * (따옴표 제외) 게시하다")*? 그 때문에 예외가있었습니다. (모르겠다. 아마도 임베디드 문서를 선언하는 오래된 방법 일 것이다) – makaron

4

임베디드 문서는 문서 인스턴스와 별도로 개별 인스턴스로 존재하지 않습니다. 즉, 포함 된 문서를 저장하려면 포함 된 문서 자체를 저장해야합니다. 그것을 보는 또 다른 방법은 실제 문서없이 임베디드 문서를 저장할 수 없다는 것입니다.

특정 임베디드 문서가 포함 된 문서를 필터링 할 수는 있지만 일치하는 임베디드 문서 자체는받지 못합니다. 일부인 전체 문서를 받게됩니다.

thread = Thread.objects.first() # Get the thread 
post = Post() 
post.attribute = "noodle" 
thread.posts.append(post) # Append the post 
thread.save() # The post is now stored as a part of the thread 
+1

을 참조하십시오. 그러나 OP는 그가'post.save()'를 내보내는 경우 빈 포스트 객체가 저장되었다고 말합니다. –

+0

게시물에 대한 감사하지만 빈 게시물 개체에 문제가 여전히 있습니다 – Ron

+1

테스트 케이스를 작성하여 작동 중임을 표시했습니다 ... – Ross