Search code examples
pythonfiltersqlalchemywhere-clause

Filtering out SQAlchemy query with group_by based on column value being > 0


I am trying to filter out this SQLAlchemy query to only return records where avg_3d_perf > 0

Here is a query I am using:

query = query.with_entities(func.max(Signals_light.id).label('id'),Signals_light.symbol,func.max(Signals_light.close).label('close'),func.max(Signals_light.volume).label('volume'),func.max(Signals_light
            .total_change).label('total_change'),func.max(Signals_light.strength).label('strength'),func.max(Signals_light.created_at).label('created_at'),func.max(Signals_light.window_mins).label('window_mins'),
            func.max(Signals_light.pattern).label('pattern'),func.max(Signals_light.pattern_type).label('pattern_type'),func.max(Signals_light.sentiment).label('sentiment'),func.avg(func.nullif(Signals_light.avg_3d_perf,0)).label('avg_3d_perf'),
            func.count(Signals_light.symbol).label('signals_count')).group_by(Signals_light.symbol)

All I need to do is filter the results from this query above to only keep records where avg_3d_Perf > 0

I tried using statements like query = query.filter(avg_3d_Perf > 0).all() on top of this large query but I think I need to apply this filter differently somehow.

I also tried to add .having(avg_3d_perf > 0) to the end of the query but it does not work either.


Solution

  • Adding query = query.having(func.avg(func.nullif(Signals_light.avg_3d_perf,0)) > 0) after the main query solved my issue.