有没有办法在couchdbkit中查找父对象?

时间:2010-11-27 22:33:46

标签: python couchdb couchdbkit

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

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

2 个答案:

答案 0 :(得分:1)

我刚刚和couchdbkit的作者聊过,显然我现在不支持我想做的事。

答案 1 :(得分: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],并担心自上次致电_parent以来您是否添加了get_children个孩子。

相关问题