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

fusionstrings picture fusionstrings · Apr 9, 2012 · Viewed 10k times · Source

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.

Answer

mjibson picture mjibson · Apr 9, 2012