将 ndb 自定义属性中的值解析为 None [英] Parse value to None in ndb custom property
本文介绍了将 ndb 自定义属性中的值解析为 None的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个自定义的 ndb 属性子类,它应该将空字符串解析为 None.当我在 _validate 函数中返回 None 时,None 值将被忽略并且仍然使用空字符串.
我可以以某种方式将输入值转换为 None 吗?
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)
推荐答案
我的实现覆盖了 _set_value 方法.Appengine 文档中没有记录这一点,但它确实有效.
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)
这篇关于将 ndb 自定义属性中的值解析为 None的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文