问题
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