views:

258

answers:

2

I need to be able to make a tree like structure in the appengine database.
I have try to make an object reference itself but have not gotten it to work.

class Item(db.Model):
    children = db.ListProperty(db.ReferenceProperty(Item))
A: 

Here is a related topic from the google-appengine group.

You can store a reference to the parent node in each child, instead of references to the child nodes in the parent.

Here's some code:

class Node(db.Model):
    pass

...snip...

root = Node()
db.put(root)

for i in xrange(10):
    child = Node(parent=root)
    db.put(child)

    for i in xrange(5):
        grandchild = Node(parent=child)
        db.put(grandchild)

parent is a special field on a Model which tells the datastore that an entity has a parent-child relationship with its parent.

From the docs:

When the application creates an entity, it can assign another entity as the parent of the new entity, using the parent argument in the Model constructor. Assigning a parent to a new entity puts the new entity in the same entity group as the parent entity.

An entity without a parent is a root entity. An entity that is a parent for another entity can also have a parent. A chain of parent entities from an entity up to the root is the path for the entity, and members of the path are the entity's ancestors. The parent of an entity is defined when the entity is created, and cannot be changed later.

Jason Hall
You should not use parent/child relationships in the datastore unless the entities need to be in the same transactional domain (entity group).
Nick Johnson
+1  A: 

Alternatively, you can store references to children in the parent with:

class Node(db.Model):
    children = db.ListProperty(db.Key)

This answer shamelessly stolen (with credit!) from Nick Johnson's answer to this related question

Jason Hall