Parse value to None in ndb custom property

最后都变了- 提交于 2019-12-11 19:29:25

问题


I have a custom ndb property subclass which should parse an empty string to None. When I return None in the _validate function, the None value is ignored and the empty string is still used.
Can I somehow cast input values to None?

class BooleanProperty(ndb.BooleanProperty):
    def _validate(self, value):
        v = unicode(value).lower()
        # '' should be casted to None somehow.
        if v == '':
            return None
        if v in ['1', 't', 'true', 'y', 'yes']:
            return True
        if v in ['0', 'f', 'false', 'n', 'no']:
            return False
        raise TypeError('Unable to parse value %r to a boolean value.' % value)

回答1:


Maybe you are looking for something like ndb.ComputedProperty?

class YourBool(ndb.Model):
    my_input = StringProperty()
    val = ndb.ComputedProperty(
        lambda self: True if self.my_input in ["1","t","True","y","yes"] else False)



回答2:


My implementation overrides the _set_value method. This is not documented by the Appengine docs, but it works.

class MyBooleanProperty(ndb.BooleanProperty):
    def _set_value(self, entity, value):
        if value == '':
            value = None
        ndb.BooleanProperty._set_value(self, entity, value)


来源:https://stackoverflow.com/questions/18204161/parse-value-to-none-in-ndb-custom-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!