【问题标题】:Implicit dict to ndb.Model conversion in Python Google App EnginePython Google App Engine 中的隐式 dict 到 ndb.Model 转换
【发布时间】:2016-11-19 06:54:51
【问题描述】:

我遇到了这个功能(?),其中字典被隐式转换为 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}

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

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

【问题讨论】:

    标签: python google-app-engine google-cloud-datastore app-engine-ndb dev-appserver-2


    【解决方案1】:

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

    您的代码只需稍作改动即可不必依赖该行为:

    user.dob = DateOfBirth(**{"day": 12, "month": 10, "year": 1983})
    

    【讨论】:

    • 这是有意的。事实上,解压 dict(或使用 dict 调用 populate)是继续创建实体的简单方法。
    猜你喜欢
    • 2013-03-02
    • 2011-07-31
    • 2011-03-22
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 2019-05-18
    • 1970-01-01
    • 2012-10-11
    相关资源
    最近更新 更多