我目前在一个项目中使用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是我想要的,但是我找不到它的文档。
答案 0 :(得分:1)
如何使用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.com