从字段数据中获取无内容,而不是空字符串 [英] Get None from a Fields data in instead of an empty string

查看:77
本文介绍了从字段数据中获取无内容,而不是空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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代码中. nullcoalesce可以轻松解决此问题.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆