去除 `peewee` `Model` 字段的空白

问题描述 投票:0回答:2

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
python peewee
2个回答
0
投票

为了能够清除空白区域,您需要在课堂上使用

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

0
投票

是你想要的吗?

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
© www.soinside.com 2019 - 2024. All rights reserved.