Get None from a Fields data in instead of an empty string

邮差的信 提交于 2019-12-08 18:16:00

问题


I have this field in the WTForms form

name = StringField('Name', validators = [Optional(), Length(max = 100)])

When the field is submitted empty then form.name.data will, as expected, contain an empty string.

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)

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.


回答1:


There is the filters parameter to the Field constructor

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



来源:https://stackoverflow.com/questions/21831216/get-none-from-a-fields-data-in-instead-of-an-empty-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!