Google App Engine - 数据存储区 - GQL查询

时间:2011-07-13 13:28:50

标签: google-app-engine gqlquery

class ProjectCategory(db.Model):
    name = db.StringProperty("Category name", required = True)

    def __str__(self):
        return str(self.name)

class Project(db.Model):
    name = db.StringProperty("Name", required = True)
    category = db.ReferenceProperty(ProjectCategory)  
    description = db.TextProperty("Description", required = True)
    #file_name = db.StringProperty("File name", required = True)
    file = db.BlobProperty("Image")

    whenstarted = db.DateTimeProperty("Start time")
    whenended = db.DateTimeProperty("End Time")

    def __str__(self):
        return str(self.title)

如何获取所有类别为CatName的项目

db.GqlQuery("SELECT * FROM Project WHERE category = :1", "CatName")

不起作用?

1 个答案:

答案 0 :(得分:4)

查询不起作用,因为您传递的是"CatName"字符串而不是ProjectCategory实例的密钥。

首先从数据存储中检索您想要的ProjectCategory实体:

pjc =  GqlQuery("SELECT * FROM ProjectCategory WHERE name = :1", "CatName").get()

然后在查询中将其用作参数:

db.GqlQuery("SELECT * FROM Project WHERE category = :1", pjc.key())

第二种方法是使用modelname_set实例的隐式ProjectCategory属性:

pjc =  GqlQuery("SELECT * FROM ProjectCategory WHERE name = :1", "CatName").get()

pjc.project_set.fetch(10) #should contains some CatName projects