将字符串变量传递给gql查询

时间:2012-06-24 08:36:22

标签: python google-app-engine google-cloud-datastore gql

我如何通过python将字符串变量传递给GQL?我可以在SQL中做得很好,但它不起作用。这就是我所拥有的:

personalposts = db.GqlQuery("select * from PersonalPost where user_id = %s order by created desc limit 30" % user_id)

这一直在杀我,但我觉得应该很简单。

谢谢!

3 个答案:

答案 0 :(得分:8)

这应该有效:

personalposts = db.GqlQuery("select * from PersonalPost where user_id =:1 order by created desc limit 30",user_id)

GqlQuery语法示例:

q = GqlQuery("SELECT * FROM Song WHERE composer = 'Lennon, John'")

q = GqlQuery("SELECT __key__ FROM Song WHERE composer = :1", "Lennon, John")

q = GqlQuery("SELECT * FROM Song WHERE composer = :composer", composer="Lennon, John")

来源: https://developers.google.com/appengine/docs/python/datastore/gqlqueryclass

答案 1 :(得分:2)

参数可以按位置或名称绑定,请查看GqlQuery类文档以获取更多信息。

所以你可以做到

personalposts = db.GqlQuery("select * from PersonalPost where user_id = :1 order by created desc limit 30", user_id)

personalposts = db.GqlQuery("select * from PersonalPost where user_id = :id order by created desc limit 30", id = user_id)

答案 2 :(得分:1)

创建一个这样的查询:

query = PersonalPost.all()
query.filter('user_id', user_id)
query.order('-created')

或使用:在'%s'周围使用单引号!!

personalposts = db.GqlQuery("select * from PersonalPost where user_id = '%s' order by created desc" % user_id)