简体   繁体   中英

SQLAlchemy hybrid_property order_by using text

Given the following Model

class Person(db.Model):
    __tablename__ = 'persons'

    name = db.Column(db.String(10), nullable=False)
    age = db.Column(db.Integer(), nullable=False)

    def __init__(self):
        self.name = ''
        self.age = 0

    @hybrid_property
    def is_configured(self):
        return self.name != '' and self.age > 0

Is it possible to construct a query using order_by on is_configured hybrid_property using sqlalchemy.text ?

If we use the ORM to order_by it works

result = Person.query.filter(or_(*some_filters)).order_by(Person.is_configured).all()

Using sqlalchemy.text results in SQL error stating no column persons.is_configured

result = Person.query.filter(or_(*some_filters)).order_by(text('persons.is_configured asc')).all()

UPDATE 2021-07-16
Some background on why this question was opened: We have a template that renders a table for user accounts where some of the columns are fields on related tables. Clicking the header of a column will sort by the column, sending request to the server with table_name.column to order_by. We have one case where the column is a property. We'd like to make this a hybrid_property so we can query and order by it. We could make this work by mapping the text to the ORM, but if there is a way to make it work with the text that the view provides that would be preferred.

No, this is not possible. The TextClause is pure SQL and executed against the database. As the hybrid property is an ORM object the database doesn't know anything about this.

Ps: There are a few ways to achieve what you want but maybe elaborate a bit more about what you are trying to achieve

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM