给定这个模型课
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")
但是不知道如何吸引ALL
学生。我看过谷歌给出的例子,但仍然迷失了方向。我知道这一次我需要一个循环,但这就是我能想出的一切。赞赏。
您将需要执行查询,并且取决于在单个请求中返回多少实体的实体将是不可能或不实际的。然后,您将需要在查询中使用游标。
您应该阅读ndb文档中的“查询”部分-它们清楚地说明了需要执行的操作-https: //developers.google.com/appengine/docs/python/ndb/queries
一个简单的查询所有项目并返回所需的详细信息作为Json记录列表的方法,您可以使用查询的map方法执行以下操作,该方法调用提供的函数或类方法。它不期望使用实体的方法,这就是为什么我不直接使用toJSON的原因。
def callback(student):
return student.toJSON())
results = Student.query().map(callback)
您可能需要弄乱toJSON方法,看看运行它时的结果。results
可能还需要显式转换为json,因此您可能需要将显式json.encode推迟到运行查询之后。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句