Why doesn't my GQL query return any results in my GAE App?
I have mostly followed a tutorial about how to build a gustbook using GAE and Python. Now I only want to show the entries from a particular day, but the GQL query doesn't return anything (although there are entries from that day):
class Shout(db.Model):
message= db.StringProperty(required=True)
when = db.DateTimeProperty(auto_now_add=True)
who = db.StringProperty()
class MainHandler(webapp.RequestHandler):
def get(self):
shouts = db.GqlQuery("SELECT * FROM Shout WHERE when=DATE('2010-11-05')")
# Return something without the WHERE clause
values = {'shouts':shouts}
self.response.out.write(template.render('main.开发者_高级运维html',values))
def post(self):
self.response.out.write("posted")
shout = Shout(message=self.request.get("message"),who=self.request.get("who"))
shout.put()
This is my main.html:
<form method="post">
<input type="text" name="who"></input>
<input type="text" name="message"></input>
<input type="submit" value="Send"> </input>
</form>
{% for shout in shouts %}
<div>{{shout.message}} from {{shout.who}} on {{shout.when}}</div>
{% endfor %}
There might be another way around this, but I think that because your when
property is a datetime you would be better served with something like this:
shouts = db.GqlQuery("""SELECT *
FROM Shout
WHERE when >= DATE('2010-11-05')
AND when < DATE('2010-11-06')""")
Try this:
shouts = db.GqlQuery("SELECT * FROM Shout WHERE when=DATE('2010-11-05')").fetch(5000)
While it is possible to use a Query object as an iterable, it is a better idea to explicitly fetch the rows and not depend on the for
in your template to do the work. I suspect that it is not supported in that way.
EDIT: Now that I look more closely at this, I suspect that the problem is that the field you are querying on is a DateTimeProperty, and by using the DATE operator, you are essentially saying that you want 2010-11-05 00:00:00, and there are no records with that exact date and time, so try this instead:
shouts = db.GqlQuery("SELECT * FROM Shout WHERE when >= DATETIME('2010-11-05 00:00:00') and when <= DATETIME('2010-11-05 23:59:59')")
精彩评论