TypeError: can't compare datetime.date to DateProperty

TypeError: can't compare datetime.date to DateProperty

我想查询某个日期是否属于特定日期范围。源代码示例:

billing_period_found = BillingPeriod.query(
        ndb.AND(
            transaction.date > BillingPeriod.start_date,
            transaction.date < BillingPeriod.end_date)
        ).get()

数据定义:

class Transaction(ndb.Model):
    date = ndb.DateProperty(required=False)

class BillingPeriod(ndb.Model):
    start_date = ndb.DateProperty(required=False)
    end_date = ndb.DateProperty(required=False)

出现以下错误: 类型错误:无法将 datetime.date 与 DateProperty

进行比较

消息错误确实有意义,因为 datetime 与 DateProperty 不同。但是,如您所见,transaction.date 的定义不是日期时间,因此我不知道这种将日期时间转换为日期的尝试的来源。无论如何 - 如果我弄清楚如何将日期时间转换为 DateProperty,我想它会解决问题。

关于如何解决这个问题有什么想法吗?

谢谢!

App Engine 数据存储不允许对多个属性进行不等式查询(不是 ndb 的限制,而是底层数据存储的限制)。选择包含特定日期的日期范围实体是一个典型的任务示例,这使得它无法在单个查询中实现。

查看 Optimizing a inequality query in ndb over two properties 以获取此问题的示例,并在答案中提出一个可能有效的建议:查询(在您的情况下)具有 [=12= 的所有 BillingPeriod 实体] 大于所需日期,可能只是为了获得他们的密钥和 start_date 的预测;然后,在您自己的应用程序中,仅 start_date 小于所需日期的 select(如果您只想要其中一个,则迭代器上的 next 将停止为一旦它找到一个)。

编辑:上面的问题是此代码的问题#1;解决后,问题 #2 出现了——正如 https://cloud.google.com/appengine/docs/python/ndb/queries 中清楚列出的那样,属性 是 ndb 查询始终位于比较的 左侧 操作员。所以,不能做 date < BillingPeriod.end_date,因为 右边 会有 属性;相反,一个 BillingPeriod.end_date > date.