GAE NDB日期范围查询未按预期工作

时间:2017-11-10 15:14:49

标签: google-app-engine app-engine-ndb

我正在尝试查询日期范围内的所有实体。我的理解是你可以在一个datetime属性上有两个不等式过滤器,但它对我不起作用。

我正在尝试查询未来2-3天的所有实体。我创建了5个实体,1个之前,3个和1个日期范围之后。创建5个实体后,我运行以下命令来测试查询:

# 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

以上结果如下:

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

我无法弄清楚日期范围查询为何包含日期范围之外的实体。

1 个答案:

答案 0 :(得分:2)

啊,我刚想通了......查询有一个特殊的ndb.AND所以范围查询应该是

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