How to query parent entity from child entity in Google App Engine (Python) NDB/Datastore?
Asked Answered
V

1

12

My question is very fundamental, I want to know straight forward and right way to access attribute values of parent entity from a child in App Engine Python. For example I have following model schema. I am using Python 2.7 and NDB.

class Gallery(ndb.Model):
    category    = ndb.StringProperty()
    title       = ndb.StringProperty()
    subtitle    = ndb.StringProperty()

class Image(ndb.Model):
    blob_key    = ndb.BlobKeyProperty()
    title       = ndb.StringProperty()
    gallery     = ndb.StringProperty()
    is_slider   = ndb.StringProperty()

Here "Gallery" is parent of "Image". They form an entity group Exhibition=>Gallery=>Image. I want to display images from Image model along with gallery detail they belong. I can access child entity from a parent (Image from Gallery) but not vice versa. I don't want to use Image model as StructuredProperty in Gallery model. I am displaying images most of the time from all images based on other flags than gallery (one situation is generating a slideshow from all images if is_slider="yes". so querying from Image directly) but still want to display info of related gallery that's why I want to know how to access parent data.

I feel this is a very generic problem and looking for a simple solution like direct access to parent than going back to top of entity group and query Gallery model with some complex logic. Any help is appreciated.

Vogeley answered 9/4, 2012 at 0:15 Comment(0)
B
31

Use: image_instance.key.parent().get()

https://developers.google.com/appengine/docs/python/ndb/keyclass#Key_parent

Baccalaureate answered 9/4, 2012 at 0:36 Comment(3)
Thanks Mjibson. it's exactly what i was missing.Vogeley
How to use it inside template loop (when loop is on image instance)? I am using Jinja 2.Vogeley
If you have a question, ask a question, don't post one as a comment.Baccalaureate

© 2022 - 2024 — McMap. All rights reserved.