one-to-many GQL query and putting results into a dictionary

喜欢而已 提交于 2019-12-12 03:16:09

问题


I have a google database called Main.

class Main(db.Model):
  name = db.StringProperty()
  phone = db.StringProperty()

There's another database Photo which references Main through a one-to-many relationship.

class Photo(db.Model):
  main = db.ReferenceProperty(Main,collection_name='photos')
  photo1 = db.StringProperty()
  photo2 = db.StringProperty()

I was wondering if anyone knows how to make a dictionary, based on the query of Main (example shown below):

class Name(webapp.RequestHandler):
  def get(self):
    names = db.GqlQuery('SELECT * FROM Main WHERE name=:1 LIMIT 1','Alan')
    values = {'names':names}
    self.response.out.write(template.render('base.html', values))

So the goal of the query above is to find the name 'Alan'. The goal of the query I don't know how to do should be to retrieve photo1 and photo2 (when name='Alan') in the class Photo and put it into a dictionary.

Thanks in advance for your help!


回答1:


It's a bit difficult to figure out what you want to achieve with the information you provided. Perhaps you can clarify further. But for now, is this what you mean?

class Name(webapp.RequestHandler):
  def get(self):
    names = db.GqlQuery('SELECT * FROM Main WHERE name=:1 LIMIT 1','Alan')
    photo_array = [] #initialize an array to store the photos dicts
    for name in names:
      for photos in name.photos: #go over all the Photo entities that reference 'Alan'
        #retrieve and put in a dictionary, and append to the photo_array
        photo_array.append({"photo1":photos.photo1, "photo2": photos.photo2})
    values = {'names':names, 'photos': photo_array}
    self.response.out.write(template.render('base.html', values))


来源:https://stackoverflow.com/questions/10222742/one-to-many-gql-query-and-putting-results-into-a-dictionary

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