【问题标题】:Query google app engine datastore for all entities查询所有实体的谷歌应用引擎数据存储
【发布时间】:2014-05-10 08:23:25
【问题描述】:

给定这个模型类

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。我已经阅读了谷歌给出的examples,但我仍然迷路了。我知道这一次我需要一个循环,但这就是我所能做的提出来。任何想法都会被欣赏。

【问题讨论】:

    标签: python google-app-engine app-engine-ndb


    【解决方案1】:

    您将需要执行查询,并且取决于有多少实体在单个请求中返回所有这些查询,这要么是不可能的,要么是不切实际的。然后,您需要在查询中使用游标。

    您应该阅读 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 推迟到运行查询之后。

    【讨论】:

      猜你喜欢
      • 2014-10-21
      • 2011-02-10
      • 1970-01-01
      • 1970-01-01
      • 2013-05-17
      • 1970-01-01
      • 1970-01-01
      • 2014-10-30
      • 1970-01-01
      相关资源
      最近更新 更多