put the following block below the `query` assignment at the top:

~~~~python
pilots_query = db.session.query(func.count(distinct(Flight.pilot_id)))
~~~~

and in the club and airport conditions copy the `query = query.filter(...)` assignments and replace `query` by `pilots_query`

after that change the `sum_pilot` assignment to `sum_pilots = 0 if page == 'pilot' else pilots_query.scalar()`