6

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!

clifgray
  • 4,313
  • 11
  • 67
  • 116

3 Answers3

8

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

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
2

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)
Harald Brinkhof
  • 4,375
  • 1
  • 22
  • 32
1

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) 
voscausa
  • 11,253
  • 2
  • 39
  • 67
  • is either one of these technically better? I can get both to work. is one faster than the other? – clifgray Jun 25 '12 at 01:59
  • I've tried this at the moment and you actually need to skip the single quotes now and just put %s then the variable after double quotes ends(no comma there also). – Belhor Jun 17 '13 at 12:49