Question

How in the world do I pass a string variable into GQL with python?? I can do it fine in SQL but it just isn't working. here is what I have:

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

This has been killing me but should be really simple I feel.

Thanks!

Was it helpful?

Solution

This should work:

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

GqlQuery syntax examples:

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")

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

OTHER TIPS

parameters can be bound by position or name, look at the GqlQuery class documentation for more info.

So you could do

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

or

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

Create a query like this:

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

or use: WITH single quotes around '%s' !!

personalposts = db.GqlQuery("select * from PersonalPost where user_id = '%s' order by created desc" % user_id) 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top