简体   繁体   中英

Google appengine datastore tree structure

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))

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM