In peewee
I have a model where I want to strip
the white space of some fields when an instance is created. Is it possible to do this?
e.g.
import peewee as pw
class Person(pw.Model):
email = pw.CharField()
name = pw.CharField()
mom = Person(email=" [email protected] ", name=" Stella Bird ") # <- white space should be stripped automatically
To be able to clear out the white space you will need to use strip()
in your class. Start by making an __init__
function in your class that takes in positional and keyword arguments.
class Person(pw.Model):
email = pw.CharField()
name = pw.CharField()
def __init__(self, *args, **kwargs):
kwargs["email"] = kwargs.get("email", "").strip()
kwargs["name"] = kwargs.get("name", "").strip()
super().__init__(*args, **kwargs)
This will strip the white space from the email
and name
.
The output with no white space:
mom = Person(email=" [email protected] ", name=" Stella Bird ")
print(mom.email)
print(mom.name)
-----------------------------------------------------------------
[email protected]
Stella Bird