我正在尝试使用column_property分配列时将列转换为float:
class voteinfo(Base):
__tablename__ = 'voteinfo'
id = Column(Integer, primary_key=True)
upvotes = Column(Integer)
downvotes = Column(Integer)
controversial = column_property(float(upvotes - downvotes)/(abs(upvotes + downvotes)+1)
def __init__(self, upvotes, downvotes):
self.upvotes = upvotes
self.downvotes = downvotes
但是,当我运行它时,我收到以下错误:
TypeError: float() argument must be a string or a number
有更好的方法吗?我正在使用column_property,因为我希望能够通过争议来排序。
答案 0 :(得分:3)
从sqlalchemy docs开始,最好的方法是定义python @property
。您还需要使用内置的sqlalchemy浮点类型。
from sqlalchemy.types import Float
class voteinfo(Base):
__tablename__ = 'voteinfo'
id = Column(Integer, primary_key=True)
upvotes = Column(Integer)
downvotes = Column(Integer)
@property
def controversial(self):
return Float(self.upvotes - self.downvotes)/Float(abs(self.upvotes + self.downvotes)+1)
def __init__(self, upvotes, downvotes):
self.upvotes = upvotes
self.downvotes = downvotes