Python 查询所有实体的google app engine数据存储
给定这个模型类Python 查询所有实体的google app engine数据存储,python,google-app-engine,app-engine-ndb,Python,Google App Engine,App Engine Ndb,给定这个模型类 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(s
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)
我试图运行一个查询来返回所有学生的名字,以及JSON格式的每个学生的分数
我已经在数据存储上运行了一个查询,并且能够检索到关于每个学生的信息
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")
但我不知道如何获取所有学生的
。我读过谷歌给出的,但仍然迷路了。我知道这一次我需要一个循环,但这就是我能想到的。任何想法都会得到回应。你需要执行一个查询,而且取决于在一个请求中返回所有请求的实体的数量,这要么是不可能的,要么是不切实际的。然后需要在查询中使用游标
您应该阅读ndb文档中的查询部分-他们清楚需要做什么-
对所有项目进行简单查询,并将所需的详细信息作为Json记录列表返回,您可以使用查询的map方法执行以下操作,该方法调用提供的函数或classmethod。它不需要实体的方法,这就是我不直接使用toJSON的原因
def callback(student):
return student.toJSON())
results = Student.query().map(callback)
您可能需要修改toJSON方法,看看运行它时结果是什么样子results
可能还需要显式转换为json,因此您可能希望将显式的json.encode延迟到运行查询之后