1

我在 couchdbkit 中遇到过很多这样的问题——据我所知,couchdbkit Document 对象下的子对象没有对父对象的引用。我希望我错了:

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()

现在我一直在做的是传递父对象,但我不喜欢这种方法。

4

2 回答 2

1

我刚刚和 couchdbkit 的作者聊天,显然现在不支持我正在尝试做的事情。

于 2010-11-27T23:17:04.513 回答
1

我有时会在 parent 上编写一个get_childorget_children方法,_parent在返回之前设置一个属性。IE:

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)orp.get_children()[3]和担心_parent自上次调用以来是否添加了没有 s 的孩子get_children

于 2010-12-03T17:27:29.670 回答