Prakhar
Prakhar

Reputation: 3536

Debugging GQL Queries

I have been trying to run this query:

my_post = db.GqlQuery("SELECT * FROM Post where __key__ = KEY('Post', 1)")
self.render("showpost.html", my_post = my_post)

and my template showpost.html looks like this:

<div class="post">
  <h3 class="post-subject">{{ my_post.subject }}</h3>
  <div class="post-content">{{ my_post.content }}</div>
</div

Instead of getting the details of the Post of id=1 I'm getting a blank page. Although there exists a post with id=1 i'm not sure how to confirm if the GQLquery is actually returning something. Is there a way to check? On trying the following:

my_post = db.GqlQuery("SELECT * FROM Post where subject = 'hello_world')
self.render("showpost.html", my_post = my_post)

I get the same issue (blank page), even though there is post who's subject is hello_world

Thanks a lot

Upvotes: 0

Views: 287

Answers (2)

Adam Crossland
Adam Crossland

Reputation: 14213

Bernie is right in that you need to use .fetch or .get to actually retrieve results from the GqlQuery that you created, but for the first version, where you have a key or an id, you don't want to create a query at all. Rather, use the methods that are provided for using them directly.

If you have an id, use:

my_post = Post.get_by_id(id)

this will be much faster than using a query object.

If you have an entire key, use:

my_post = Post.get(key)

That is the fastest and most efficient way to get an entity out of the database.

Upvotes: 2

mechanical_meat
mechanical_meat

Reputation: 169494

GqlQuery is a class.
Your code has created an instance of the GqlQuery class.
To return something from the datastore you need to use either of the following instance methods:

.fetch() # requires number of entities as first argument
.get()

Example:

my_query = db.GqlQuery("SELECT * FROM Post WHERE subject = :subject", 
                       subject="hello_world")
my_post = my_query.get() # the magic happens here
self.render("showpost.html", my_post = my_post)

Upvotes: 2

Related Questions