Brandon
Brandon

Reputation: 3136

How to compare a python date against a DateTimeProperty in an NDB query

I'm having some difficulty trying to use a python date object to filter against a DateTimeProperty in an NDB query. I realize that the DateTimeProperty (some_date) does not have a date property, but is there something simple I can do that looks like the following:

cls.query(supplied_date == cls.some_date.date).fetch()

Upvotes: 5

Views: 2016

Answers (1)

Greg
Greg

Reputation: 10360

It isn't possible without changing your model.

The simplest option would be to use two inequality filters on the datetime property (> date 00:00 and <= date 23:59), but then you couldn't use any other inequality in your queries.

The (an?) other option is to introduce a second property that contains the date value that you filter against:

class YourModel(ndb.Model):
  some_datetime = ndb.DateTimeProperty()
  some_date = ndb.ComputedProperty(lambda self: self.some_datetime.date)

If you only ever need to filter by date, then your datetime property can have indexed=False, but otherwise you'll have the cost of an extra index.

Upvotes: 3

Related Questions