Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy - using hybrid properties in a query

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())

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?

like image 273
Abhishek Chanda Avatar asked Feb 27 '17 12:02

Abhishek Chanda


People also ask

What is SQLAlchemy hybrid property?

“hybrid” means the attribute has distinct behaviors defined at the class level and at the instance level. The hybrid extension provides a special form of method decorator, is around 50 lines of code and has almost no dependencies on the rest of SQLAlchemy.

How does the querying work with SQLAlchemy?

Python Flask and SQLAlchemy ORM All SELECT statements generated by SQLAlchemy ORM are constructed by Query object. It provides a generative interface, hence successive calls return a new Query object, a copy of the former with additional criteria and options associated with it.

Should I use SQLAlchemy core or ORM?

If you want to view your data in a more schema-centric view (as used in SQL), use Core. If you have data for which business objects are not needed, use Core. If you view your data as business objects, use ORM. If you are building a quick prototype, use ORM.

What is lazy dynamic SQLAlchemy?

lazy = 'dynamic': When querying with lazy = 'dynamic', however, a separate query gets generated for the related object. If you use the same query as 'select', it will return: You can see that it returns a sqlalchemy object instead of the city objects.


1 Answers

You need to create expression

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)
like image 50
r-m-n Avatar answered Oct 05 '22 02:10

r-m-n