SQLAlchemy - 在查询中使用混合属性 [英] SQLAlchemy - using hybrid properties in a query
本文介绍了SQLAlchemy - 在查询中使用混合属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用这样的 SQLAlchemy 混合属性
I am trying to use a SQLAlchemy hybrid property like this
class Metric(Base):
__tablename__ = 'metric'
id = Column(Integer, primary_key=True)
value = Column(Float, nullable=False)
@hybrid_property
def dominance(self):
return 1 - abs(0.5 - float(self.value))
现在,我像这样在我的模型中使用它
Now, I use this in my model like this
class MetricModel(BaseModel):
def get_dominance(self):
self.query(Metric).filter(Metric.dominance > 0.5).order_by(Metric.dominance.desc()).limit(2).all()
这是一个烧瓶应用程序,它是这样调用的
This is a flask app and it's being called like this
model = MetricModel(db)
with db.session():
print(model.get_dominant_traits())
这给了我一个错误<代码>类型错误:float() 参数必须是字符串或数字,而不是InstrumentedAttribute"从错误看来,没有结果集,因此失败.我按照这里的文档 http://docs.sqlalchemy.org/en/最新/orm/extensions/hybrid.html我应该怎么做?
This gives me an error
TypeError: float() argument must be a string or a number, not 'InstrumentedAttribute'
From the error it looks like there is no result set, hence the failure. I followed the docs here http://docs.sqlalchemy.org/en/latest/orm/extensions/hybrid.html
What should I do differently?
推荐答案
您需要创建 表达式
from sqlalchemy import func
class Metric(Base):
__tablename__ = 'metric'
id = Column(Integer, primary_key=True)
value = Column(Float, nullable=False)
@hybrid_property
def dominance(self):
return 1 - abs(0.5 - self.value)
@dominance.expression
def dominance(cls):
return 1 - func.abs(0.5 - cls.value)
这篇关于SQLAlchemy - 在查询中使用混合属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文