Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 759
Clodoaldo Neto Avatar asked Feb 17 '14 14:02

Clodoaldo Neto


People also ask

How do you replace an empty string on a None?

Simply the str function can be used to perform this particular task because, None also evaluates to a “False” value and hence will not be selected and rather a string converted false which evaluates to empty string is returned.

Is None equal to empty string?

Definition and Usage. The None keyword is used to define a null value, or no value at all. None is not the same as 0, False, or an empty string.

How do you change a string to a None in Python?

Use the boolean OR operator to convert None to an empty string in Python, e.g. result = None or "" . The boolean OR operator returns the value to the left if it's truthy, otherwise the value to the right is returned. Since None is a falsy value, the operation will return "" . Copied!

IS null same as empty string in C?

The value null represents the absence of any object, while the empty string is an object of type String with zero characters. If you try to compare the two, they are not the same.


1 Answers

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

like image 180
Clodoaldo Neto Avatar answered Sep 22 '22 13:09

Clodoaldo Neto