9

在旧的谷歌appengine数据存储API“必需”和“默认”可以一起用于属性定义。使用NDB我得到一个为什么在ndb中需要和默认是互斥的?

ValueError: repeated, required and default are mutally exclusive. 

示例代码:

from google.appengine.ext import ndb 
from google.appengine.ext import db 

class NdbCounter(ndb.Model): 
    # raises ValueError 
    count = ndb.IntegerProperty(required=True, default=1) 

class DbCounter(db.Model): 
    # Doesn't raise ValueError 
    count = db.IntegerProperty(required=True, default=1) 

我想实例化一个计数器,而无需指定值。我也想避免有人把这个值覆盖到None。上面的例子被构造。我可能没有必要的属性生活,而是添加一个增量()方法。尽管如此,我还是没有看到为什么要求和默认是相互排斥的。

它是一个错误或功能?

回答

10

我认为你是对的。也许我在写代码的那部分时感到困惑。 “required = True”的意思是“不允许写入None”,所以应该可以将其与默认值结合使用。请在NDB跟踪器中提出功能请求:http://code.google.com/p/appengine-ndb-experiment/issues/list

请注意,对于重复的属性,事情会更加复杂,重复可能会继续与要求或默认不兼容,即使实现了上述功能。

+0

谢谢。我创建了http://code.google.com/p/appengine-ndb-experiment/issues/detail?id=236问题 – bastian

0

林不知道什么目的,继承人是appengine.ext.ndb.model.py的“解释”:

The repeated, required and default options are mutually exclusive: a 
repeated property cannot be required nor can it specify a default 
value (the default is always an empty list and an empty list is always 
an allowed value), and a required property cannot have a default. 

要小心,NDB有一些其他的真的很烦人的行为(文本> 500个字节不可能没有猴子修补expando模型,通过.IN([])过滤引发异常,..)。 所以除非你需要通过缓存提高速度,否则你应该考虑使用ext.db atm。

+0

所以这似乎是一个概念性的错误。我没有看到这个限制的理由。限制应该是,如果需要,默认值不能为None = True。 – bastian

+0

对我来说这是有道理的,因为它是。如果你需要一个值,那么为什么还要指定一个默认值,因为在这种情况下你可能没有required = True(就好像你没有别的办法,只是创建并保存模型,因为它有默认值)。 required = True是对我的一个提醒,如果我试图在这个领域没有价值的情况下保存这个模型,它就会失败,而如果我提供一个默认值,它永远不会失败,对我而言,所需的。 –

相关问题