我目前正在一个项目中使用SQL Alchemy和SQL Alchemy Utils URLType,我被卡住了,试图弄清楚如何清理SQLAlchemy属性的输入,以便数据库中唯一存储的东西是furl对象的宿主。目前我已经解决了这个问题,只需在每个set操作之前调用一个类方法,如下所示:
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我想也许this answer就是我要找的东西,但是我找不到它的文档。
发布于 2019-01-13 09:55:48
使用property/setter怎么样?
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.comhttps://stackoverflow.com/questions/54165224
复制相似问题