【问题标题】:SQLAlchemy hybrid_property order_by using textSQLAlchemy hybrid_property order_by 使用文本
【发布时间】:2021-07-15 17:12:27
【问题描述】:

给定以下模型

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_configured hybrid_property 上使用sqlalchemy.text 使用order_by 构造查询?

如果我们使用 ORM to order_by 就可以了

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

使用 sqlalchemy.text 会导致 SQL 错误声明没有列 persons.is_configured

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

2021 年 7 月 16 日更新
关于为什么打开这个问题的一些背景知识:我们有一个模板,它为用户帐户呈现一个表格,其中一些列是相关表格上的字段。单击列的标题将按列排序,将带有table_name.column 的请求发送到服务器到order_by。我们有一种情况,列是一个属性。我们想让它成为一个 hybrid_property,以便我们可以通过它查询和订购。我们可以通过将文本映射到 ORM 来完成这项工作,但是如果有一种方法可以使其与视图提供的文本一起工作,那将是首选。

【问题讨论】:

    标签: python sqlalchemy


    【解决方案1】:

    不,这是不可能的。 TextClause 是纯 SQL 并针对数据库执行。由于混合属性是一个 ORM 对象,因此数据库对此一无所知。

    P.s.:有几种方法可以实现您想要的,但可能会详细说明您想要实现的目标

    【讨论】:

      猜你喜欢
      • 2018-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多