开发者

Is there a way to look up the parent object in couchdbkit?

开发者 https://www.devze.com 2023-01-27 01:16 出处:网络
I have run into this a lot in couchdbkit - as far as I can tell the child objects under a couchdbkit Document object have no reference back to the parent. I hope I am wrong though:

I have run into this a lot in couchdbkit - as far as I can tell the child objects under a couchdbkit Document object have no reference back to the parent. I hope I am wrong though:

class Child(DocumentSchema):
   开发者_JAVA百科 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()

Right now what I have been doing is passing around the parent object, but I don't like this approach.


I just chatted with the author of couchdbkit and apparently what I am trying to do is not supported now.


What I sometimes do is write a get_child or get_children method on parent that sets a _parent attribute before returning. 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

then of couse you can write code like:

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

The drawbacks of this versus having it couchdbkit are clear: you have to write these accessor methods for each sub-doc (or if you're clever write a function that will add these for you) but more annoyingly you have to always call p.get_child(3) or p.get_children()[3] and worry about whether you've added children with no _parents since the last time you've called get_children.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号