Parse value to None in ndb custom property

2019-08-21 07:35发布

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)

2条回答
做自己的国王
2楼-- · 2019-08-21 08:15

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)
查看更多
走好不送
3楼-- · 2019-08-21 08:27

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)
查看更多
登录 后发表回答