且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ndb查询错误与datetime字段 - Google App Engine

更新时间:2023-11-29 16:18:22

您可以使用范围查询。参见下面的例子。

  import datetime 
date = datetime.datetime.strptime('02 / 19/2013' '%m /%d /%Y')
kl = Dates.query(
ndb.AND(Dates.date> = date),
Dates.date< date + datetime .timedelta(days = 1))

将获取所有的datetime与02/19/2013。 p>

I'm having a problem and I don't find any information about.

I define a field in my model like this.

class Dates(ndb.model):
    ...
    date = ndb.DateTimeProperty(required = True) # I want to store date and time
    ...

Later I try a query (now I want all the dates for a day, I don'tn mind the time):

kl = Dates.query(ndb.AND(Dates.date.year == year,
                         Dates.date.month == month,
                         Dates.date.day == day),
                 ancestor = customer.key).fetch(keys_only = True)
dates = ndb.get_multi(kl)

But I get this error log: AttributeError: 'DateTimeProperty' object has no attribute 'year'

I don't know why. I've tried Dates.date() == date, Dates.date == date (<-DateTime obj), ...

My DB is still empty but I suppose this doesn't mind because I'll never have dates for every possible days.

Anybody knows why? Should I go with GQL instead?

You can use "range" queries for this. See example below.

import datetime
date = datetime.datetime.strptime('02/19/2013', '%m/%d/%Y')
kl = Dates.query(
    ndb.AND(Dates.date >= date),
            Dates.date < date + datetime.timedelta(days=1))

Will fetch all datetime's with 02/19/2013.