2010-11-27 30 views
1

我已经在couchdbkit中遇到过很多 - 据我所知,在couchdbkit下的子对象文档对象没有可以引用的父对象。我希望我是错的:有没有办法在couchdbkit中查找父对象?

class Child(DocumentSchema): 
    name = StringProperty() 
    def parent(self): 
     # How do I get a reference to the parent object here? 
     if self.parent.something: 
       print 'yes' 
     else: 
       print 'no' 

class Parent(Document): 
    something = BooleanProperty() 
    children = SchemaListProperty(Child) 

doc = Parent.get('someid') 
for c in doc.children: 
    c.parent() 

现在,我一直在做的就是绕过父对象,但我不喜欢这种方式。

回答

1

我刚和couchdbkit的作者聊天,显然我现在不支持这个功能。

1

我有时会做的是在返回之前在父级上写一个get_childget_children方法来设置_parent属性。即:

class Parent(Document): 
    something = BooleanProperty() 
    children = SchemaListProperty(Child) 
    def get_child(self, i): 
     "get a single child, with _parent set" 
     child = self.children[i] 
     child._parent = self 
     return child 
    def get_children(self): 
     "set _parent of all children to self and return children" 
     for child in self.children: 
      child._parent = self 
     return children 

然后职高,你可以编写代码:

class Child(DocumentSchema): 
    name = StringProperty() 
    def parent(self): 
     if self._parent.something: 
      print 'yes' 
     else: 
      print 'no' 

这样做的缺点与拥有它couchdbkit是明确的:你必须写为每个子文档,这些访问方法(或如果你聪明的写了一个函数,会为你添加这些),但更烦人的是,你必须始终调用p.get_child(3)p.get_children()[3],并担心自上次调用get_children以来是否添加了没有_parent的子项。

相关问题