Query google app engine datastore for all entities

一世执手 提交于 2019-12-25 02:25:08

问题


Given this model class

class Student(ndb.Model):
   student_id = ndb.IntegerProperty(required=True)
   student_name = ndb.StringProperty(required=True)
   score=ndb.IntegerProperty(required=True)

   def toJSON(self):
        jsonData = {
        "Student Id":str(self.student_id),
        "Name":self.student_name,
        "Score": str(self.score)
        }
        return json.encode(jsonData)

I am trying to run a query to return all the student names, along with the score for each student in JSON format.

I already ran a query on the datastore and was able to retrieve information regarding each student using

class ViewStudentDetailsHandler(webapp2.RequestHandler):
def get(self):
    student_id=self.request.get('id')
    callback = self.request.get('callback')
    student = Student.get_by_id(student_id)
    if student:
        if (callback):
            self.response.write(callback + '(' + student.toJSON() + ')')
        else:
            self.response.write(student.toJSON())
    else:
        if(callback):
            self.response.write(callback + "(null)")
        else:
            self.response.write("No student with that id")

But have no clue how to get ALL of the students.I have read examples given by Google, but am still lost.I know this time around i'll need a loop, but that's about all i can come up with.Any ideas would be appreaciated.


回答1:


You will need to perform a query, and depending how many entities returning all them in a single request will either not be possible or practical. You will then need to use cursors with the query.

You should read the section of Queries in the ndb docs - they are clear about what needs to be done - https://developers.google.com/appengine/docs/python/ndb/queries

A simple query for all items and to return the details you want as a list of Json records you would do the following, using the map method of a query, which calls the supplied function or classmethod. It doesn't expect a method of the entity thats why I don't use toJSON directly.

def callback(student):
    return student.toJSON())

results = Student.query().map(callback)

You may need to fiddle with your toJSON method, have a look at what results looks like when you run it. results may also need to explicitly converted to json, so you may want to defer the explicit json.encode till after after you have run the query.



来源:https://stackoverflow.com/questions/23578778/query-google-app-engine-datastore-for-all-entities

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