【问题标题】:Build a GQL query (for Google App Engine) that has a condition on ReferenceProperty构建具有 ReferenceProperty 条件的 GQL 查询(用于 Google App Engine)
【发布时间】:2010-10-25 12:31:28
【问题描述】:

假设我有以下模型:

class Schedule(db.Model):
    tripCode = db.StringProperty(required=True)
    station = db.ReferenceProperty(Station, required=True)    
    arrivalTime = db.TimeProperty(required=True)
    departureTime = db.TimeProperty(required=True)

假设我有一个 Station 对象存储在 var foo 中。

如何组装一个 GQL 查询,该查询返回所有 Schedule 对象并引用 foo 引用的 Station 对象?

这是我最好的(尽管不正确)尝试形成这样一个查询:

myQuery = "SELECT * FROM Schedule where station = " + str(foo.key())

foo 又是一个Station 对象

【问题讨论】:

    标签: python google-app-engine gql


    【解决方案1】:

    您不应使用字符串替换将用户数据插入 GQL 字符串。 GQL 支持参数替换,因此您可以这样做:

    db.GqlQuery("SELECT * FROM Schedule WHERE station = $1", foo.key())
    

    或者,使用查询接口:

    Schedule.all().filter("station =", foo.key())
    

    【讨论】:

    • FWIW,无需将 foo.key() 放在第二种情况下。这将起作用:Schedule.all().filter("station =", foo)
    【解决方案2】:

    更简单的做法是通过将“collection_name”字段添加到 ReferenceProperty 来更改模型定义:

    station = db.ReferenceProperty(Station, required=True, collection_name="schedules")

    那么你可以这样做:

    foo.schedules

    只要您想获取所有电台的时间表。

    【讨论】:

      猜你喜欢
      • 2011-07-24
      • 2010-11-16
      • 1970-01-01
      • 2013-10-13
      • 2011-08-17
      • 1970-01-01
      • 2012-07-23
      • 2012-07-12
      • 2014-03-02
      相关资源
      最近更新 更多