在
peewee
中,我有一个模型,我想在创建实例时 strip
某些字段的空白。可以这样做吗?
例如
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
为了能够清除空白区域,您需要在课堂上使用
strip()
。首先在类中创建一个 __init__
函数,该函数接受位置参数和关键字参数。
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)
这将从
email
和 name
中去除空白。
打印语句的输出没有空格:
[email protected]
Stella Bird
是你想要的吗?
import peewee as pw
class Person(pw.Model):
email = pw.CharField()
name = pw.CharField()
def __init__(self, email: str, name: str):
self.email = email.strip()
self.name = name.strip()
mom = Person(email=" [email protected] ", name=" Stella Bird ") # <- white space should be stripped automatically