简体   繁体   中英

Creating parent relationship in datastore using Google Appengine

I am trying to create a root entity with a single ancestor. When I try to get the parent key from that single ancestor I get 'None'. What am I missing here?

Here is my sample code:

        # create a single root with key_name = 'home'
        root = Page.get_or_insert('home')
        # delay added for consistency
        time.sleep(1)
        # create an ancestor with the parent key set to the key of the root
        start_page = Page(parent=root.key(), page_name="", content="<h1>welcome home</h1>")     
        start_page.put()
        time.sleep(1)

        child = Page.all().ancestor(root.key())
        utils.log('==>> %s' % child.get().key())

The line above output the key of the root, not the child.

Why is this?

When I look at the Datastore viewer on my local machine this is what I see: 数据存储视图 I dont see anything in the data of the child which refers to its parent.

My eventual aim is to have many child pages from this parent or other parents that are created. I am aware of the ReferenceProperty datatype but this seemed a more natural data model to work with and hence more Pythonic.

The key is what refers from the child to the parent. If you printed the decoded value of the child's key, you'd see something like [Page, 'home', Page, <long number>] , where "home" is the manually-allocated key name of the parent, and the long number is the automatically generated key ID of the child.

Your issue is only that querying by ancestor returns the ancestor as well as the children, and query.get() returns the first result for that query, ie the ancestor itself. If you output the result of child.fetch() you would see your child as well.

Note that adding a time.sleep doesn't do anything at all to mitigate any issues with consistency, since the dev datastore emulates eventual consistency on the basis of requests made, not time. But in any event, gets by key or by ancestor are always consistent anyway.

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