简体   繁体   English

SQLAlchemy SQL 表达式与 JSONB 查询

[英]SQLAlchemy SQL expression with JSONB query

I have the following property on a flask-sqlalchemy model.我在 flask-sqlalchemy model 上有以下属性。 I want to make this approved_at property a sortable column in flask-admin, but apparently I need to convert this to a hybrid property using SQL expressions.我想让这个approved_at属性成为flask-admin 中的可排序列,但显然我需要使用SQL 表达式将其转换为混合属性

@property
def approved_at(self):
    approved_log = (
        db.session.query(AuditLog)
        .filter_by(target_id=self.id, target_table='consult')
        .filter(AuditLog.new_values['status'].astext == "APPROVED: 5")
        .order_by(AuditLog.timestamp.desc())
        .first()
    )
    if approved_log:
        return approved_log.timestamp

I don't know how to convert this query into a sqlalchemy SQL expression, since it's pretty complex with the JSONB query in it.我不知道如何将此查询转换为 sqlalchemy SQL 表达式,因为其中的 JSONB 查询非常复杂。 I've looked at all the other SO answers, haven't been able to figure it out.我已经查看了所有其他 SO 答案,但无法弄清楚。

Can I get some help on how to do this?我可以就如何做到这一点获得一些帮助吗? Or alternatively, how to make a sortable column in Flask Admin that doesn't require me to use hybrid expressions?或者,如何在 Flask Admin 中创建一个不需要我使用混合表达式的可排序列?

Implementing it as a hybrid is somewhat straightforward:将其作为混合实现有点简单:

@hybrid_property
def _approved_at(self):
    return (
        db.session.query(AuditLog.timestamp)
        .filter_by(target_id=self.id, target_table='consult')
        .filter(AuditLog.new_values['status'].astext == "APPROVED: 5")
        .order_by(AuditLog.timestamp.desc())
        .limit(1)
    )

@hybrid_property
def approved_at(self):
    # return the first column of the first row, or None
    return self._approved_at.scalar()

@approved_at.expression
def approved_at(cls):
    # return a correlated scalar subquery expression
    return cls._approved_at.as_scalar()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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