views:

131

answers:

1

I have a scenario in which I need a self reference property as follow:

class Post(db.Model):
  creator = db.UserProperty()
  post_title = db.StringProperty(required=True)
  post_status = db.StringProperty(required=True, choices=['draft', 'published'])
  post_parent = db.SelfReferenceProperty()

Now, I want ensure that an entity shouldn't be its own parent and a child of an entity cannot be its parent. How can I ensure this kind of a relationship in the PostForm model form and the Post model.

A: 

I would suggest using a ListProperty(db.Key) instead, storing the list of ancestors. That way, you can query more efficiently ('get every descendent of node x' is easier), and you can enforce the latter condition easily, like this:

def ancestor_list_validator(l):
  if len(l) != len(set(l)):
    raise Exception("Repeated values in ancestor list!")

class Post(db.Model):
  # ...
  ancestors = db.ListProperty(db.Key, validator=ancestor_list_validator)

Validating that the entity's own key isn't in the list is a little tougher, and will likely require writing a custom datastore property.

Nick Johnson