Let's say I have two tables, A
and B
:
class Status(Enum):
COMPLETED = "COMPLETED"
FAILED = "FAILED"
class A(Base):
id = Column(String, primary_key=True)
status = Column(Enum(Status), index=True)
class B(Base):
id = Column(String, primary_key=True)
a_id = Column(String, ForeignKey('A.id'), index=True)
group_column = Column(String, primary_key=True)
I want to build a filter that will join those two tables via a_id
and group the results by group_column
, but will check that, within each grouping, all grouped rows have status == Status.FAILED
.
One way I was thinking to do this would be to use the having
function and try to filter by counting all rows and comparing with the rows that contain the expected state, so something like:
db.query(B)
.join(A)
.group_by(A.group_column)
.having(database.func.count('*') ==
database.func.count(B.sync_state == Status.FAILED))
However I am not sure how to get database.func.count
to count based on a condition, or if that's even possible. Is there some way to fix this query or do I have to try a different approach entirely?