我在 WTForms
表单中有这个字段
name = StringField('Name', validators = [Optional(), Length(max = 100)])
当字段提交为空时,form.name.data
将如预期那样包含一个空字符串。
有什么方法可以让它返回 None
而不是空字符串?只是因为像这样update
中处理数据库中的null
非常方便:
update t
set
name = coalesce(%(name)s, name),
other = coalesce(%(other)s, other)
使用上面的代码,我不需要检查字段是否为空,并在 SQL 代码中的 Python 代码中采取相应的操作。 null
和 coalesce
可以轻松解决这个问题。
最佳答案
Field
构造函数有filters
参数
name = StringField(
'Name',
validators = [Optional(), Length(max = 100)],
filters = [lambda x: x or None]
)
http://wtforms.readthedocs.org/en/latest/fields.html#the-field-base-class
关于python - 从字段数据中获取 None 而不是空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21831216/