0

我目前在一个项目中使用 SQL Alchemy 和 SQL Alchemy Utils URLType,我一直在试图弄清楚如何清理 SQLAlchemy 属性的输入,以便数据库中存储的唯一内容是 furl 对象的主机。目前我已经通过在每个集合操作之前调用一个类方法来解决它,如下所示:

class Website(Base, Timestamp):
    __tablename__ = "websites"

    id = Column(Integer, primary_key=True)

    # Data
    origin = Column(URLType, nullable=False, unique=True)

    # Functions
    @classmethod
    def prep_url(cls, url):
        return url.origin

x = furl('https://stackoverflow.com/questions/ask')
ws = Website(origin=Website.prep_url(x))
>>> ws.origin
stackoverflow.com

虽然我希望能够像这样使用它:

ws = Website(origin=x)
>>> ws.origin
stackoverflow.com

我想也许这个答案就是我想要的,但我找不到它的文档。

4

1 回答 1

1

使用属性/设置器怎么样?

class Website(Base, Timestamp):
    __tablename__ = "websites"

    id = Column(Integer, primary_key=True)

    # Data
    origin_ = Column("origin", URLType, nullable=False, unique=True)

    @property
    def origin(self):
        return self.origin_

    @origin.setter
    def origin(self, url):
        self.origin_ = url.origin

x = furl('https://stackoverflow.com/questions/ask')
ws = Website(origin=x)
>>> ws.origin
stackoverflow.com
于 2019-01-13T01:55:47.970 回答