【问题标题】:Stripping whitespace generically for all String fields - SQLAlchemy为所有字符串字段一般地去除空格 - SQLAlchemy
【发布时间】:2018-06-14 09:56:45
【问题描述】:

我通过 Flask-SQLAlchemy 使用 SQLAlchemy 作为 Web 应用程序的 ORM。

我想在分配给任何字符串字段时自动前导和尾随空格(例如str.strip)。

执行此操作的一种方法如下,但需要为每个字符串字段指定它:

class User(db.Model):
    _email = db.Column('email', db.String(100), primary_key=True)
    @hybrid_property
    def email(self): return self._email
    @email.setter
    def email(self, data): self._email = data.strip()

我想为每个字符串字段更通用地执行此操作(无需为每个字段编写上述内容)。

【问题讨论】:

标签: python orm sqlalchemy flask-sqlalchemy string-parsing


【解决方案1】:

一种方法是创建一个处理此类处理的自定义augmented string type

from sqlalchemy.types import TypeDecorator

class StrippedString(TypeDecorator):

    impl = db.String

    def process_bind_param(self, value, dialect):
        # In case you have nullable string fields and pass None
        return value.strip() if value else value

    def copy(self, **kw):
        return StrippedString(self.impl.length)

然后,您可以在模型中使用它来代替普通的 String

class User(db.Model):
    email = db.Column(StrippedString(100), primary_key=True)

这与您自己的实现并不完全相同,因为处理发生在将值作为参数绑定到查询时,或者换句话说,稍后:

In [12]: u = User(email='     so.much@white.space     ')

In [13]: u.email
Out[13]: '     so.much@white.space     '

In [14]: session.add(u)

In [15]: session.commit()

In [16]: u.email
Out[16]: 'so.much@white.space'

【讨论】:

    猜你喜欢
    • 2017-09-20
    • 1970-01-01
    • 1970-01-01
    • 2017-12-28
    • 2019-02-01
    • 2012-01-06
    • 2019-11-25
    相关资源
    最近更新 更多