minou
minou

Reputation: 16563

GAE NDB date range query not working as expected

I'm trying to query all entities within a date range. My understanding is that you can have two inequality filters on a single datetime property, but it isn't working for me.

I'm trying to query all entities with a date 2-3 days in the future. I created 5 entities, 1 before, 3 in, and 1 after the date range. After creating the 5 entities, I ran the following to test the queries:

# Define the date range
today = datetime.combine(datetime.utcnow(), time(0))
d2 = today + timedelta(days=2)
d3 = today + timedelta(days=3)
print "Start:", d2
print "End:", d3

print "All"
entities = models.Entity.query()
for e in entities:
    print e.my_date

print "Range"
entities = models.Entity.query(Entity.my_date >= d2 and Entity.my_date <= d3)
for e in entities:
    print e.my_date

print "After"
entities = models.Entity.query(Entity.my_date >= d2)
for e in entities:
    print e.my_date

print "Before"
entities = models.Entity.query(Entity.my_date <= d3)
for e in entities:
    print e.my_date

Here are the results of the above:

Start: 2017-11-12 00:00:00
End: 2017-11-13 00:00:00
All
2017-11-11 23:00:00
2017-11-12 01:00:00
2017-11-12 06:00:00
2017-11-12 12:00:00
2017-11-13 01:00:00
Range
2017-11-11 23:00:00  # Why is this selected by the query?
2017-11-12 01:00:00
2017-11-12 06:00:00
2017-11-12 12:00:00
After
2017-11-12 01:00:00
2017-11-12 06:00:00
2017-11-12 12:00:00
2017-11-13 01:00:00
Before
2017-11-11 23:00:00
2017-11-12 01:00:00
2017-11-12 06:00:00
2017-11-12 12:00:00

I can't figure out why the date range query includes an entity outside of the date range.

Upvotes: 1

Views: 246

Answers (1)

minou
minou

Reputation: 16563

Ahh, I just figured it out... There is a special ndb.AND for queries so the range query should be

entities = models.Entity.query(ndb.AND(Entity.my_date >= d2, Entity.my_date <= d3))

Upvotes: 2

Related Questions