从字段数据中获取无内容,而不是空字符串 [英] Get None from a Fields data in instead of an empty string
问题描述
我在WTForms
表单中输入了此字段
I have this field in the WTForms
form
name = StringField('Name', validators = [Optional(), Length(max = 100)])
将字段提交为空时,form.name.data
将按预期包含一个空字符串.
When the field is submitted empty then form.name.data
will, as expected, contain an empty string.
是否有某种方法可以使它返回None
而不是空字符串?只是因为像这样update
:
Is there some way to make it return None
in instead of an empty string? It is just because it is very convenient to deal with null
in the database like in this update
:
update t
set
name = coalesce(%(name)s, name),
other = coalesce(%(other)s, other)
使用上面的代码,我不需要检查该字段是否为空,并且可以采取相应的措施,无论是在SQL代码中的Python代码中. null
和coalesce
可以轻松解决此问题.
With the above code I don't need to check if the field is empty or not and take actions accordingly be it in the Python code on in the SQL code. The null
with the coalesce
solves that easily.
推荐答案
Field
构造函数有filters
参数
name = StringField(
'Name',
validators = [Optional(), Length(max = 100)],
filters = [lambda x: x or None]
)
http://wtforms.readthedocs.org/zh_CN/latest/fields.html#the-field-base-class
这篇关于从字段数据中获取无内容,而不是空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!