I have the following property on a 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.
JavaScript
x
12
12
1
@property
2
def approved_at(self):
3
approved_log = (
4
db.session.query(AuditLog)
5
.filter_by(target_id=self.id, target_table='consult')
6
.filter(AuditLog.new_values['status'].astext == "APPROVED: 5")
7
.order_by(AuditLog.timestamp.desc())
8
.first()
9
)
10
if approved_log:
11
return approved_log.timestamp
12
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. I’ve looked at all the other SO answers, haven’t been able to figure it out.
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?
Advertisement
Answer
Implementing it as a hybrid is somewhat straightforward:
JavaScript
1
20
20
1
@hybrid_property
2
def _approved_at(self):
3
return (
4
db.session.query(AuditLog.timestamp)
5
.filter_by(target_id=self.id, target_table='consult')
6
.filter(AuditLog.new_values['status'].astext == "APPROVED: 5")
7
.order_by(AuditLog.timestamp.desc())
8
.limit(1)
9
)
10
11
@hybrid_property
12
def approved_at(self):
13
# return the first column of the first row, or None
14
return self._approved_at.scalar()
15
16
@approved_at.expression
17
def approved_at(cls):
18
# return a correlated scalar subquery expression
19
return cls._approved_at.as_scalar()
20
JavaScript
1
1
1