1

我遇到了这个功能(?),其中字典被隐式转换为 ndb.Model 对象

我有以下 ndb.Model 类

class DateOfBirth(ndb.Model)
  day = ndb.IntegerProperty()
  month = ndb.IntegerProperty()
  year = ndb.IntegerProperty()

class User(ndb.Model):
   dob = ndb.StructuredProperty(DateofBirth)

在一个地方我不小心传入了一个字典

user.dob = {"day": 12, "month": 10, "year": 1983}

它没有抱怨,看起来很有效。

这是意料之中的,还是我预计以后会遇到问题(因为这种行为没有记录在案并且预计会随时中断)

4

1 回答 1

3

这对我来说是一个惊喜,我已经使用 NDB 很长时间了!但从代码来看,它似乎是有意的:https ://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/caac0c3e7dd4d9b2c6b32dfc5d59386dd02e6b57/ndb/model.py#L2354

不过,不必依赖行为,这只是对您的代码的一个小改动:

user.dob = DateOfBirth(**{"day": 12, "month": 10, "year": 1983})
于 2016-11-19T09:19:57.633 回答