Query google app engine datastore for all entities

2019-09-14 22:29发布

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条回答
ら.Afraid
2楼-- · 2019-09-14 23:22

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.

查看更多
登录 后发表回答