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))
Matthew FL
  • 1,612
  • 3
  • 18
  • 22
  • And just what kind of tree have nodes referencing themselves – Alex Jasmin Apr 09 '10 at 03:49
  • The nodes themselves aren't referencing themselves in his code snippet, but the `Node` class needs to reference other `Node` objects to make a tree. Instead, a child should reference its parent (see my answer) – Jason Hall Apr 09 '10 at 03:59

2 Answers2

3

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

Community
  • 1
  • 1
Jason Hall
  • 20,632
  • 4
  • 50
  • 57
1

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.

Community
  • 1
  • 1
Jason Hall
  • 20,632
  • 4
  • 50
  • 57
  • 2
    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 Apr 09 '10 at 07:40