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

纵饮孤独 提交于 2019-11-30 13:53:10

问题


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.


回答1:


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

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



来源:https://stackoverflow.com/questions/10067624/how-to-query-parent-entity-from-child-entity-in-google-app-engine-python-ndb-d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!