code: def fast_count(query):
      
      count_query = (query
                     .statement.with_only_columns([func.count()]).order_by(None))
      count = query.session.execute(count_query).scalar()
      return count
docs: It turns out the built-in SQLAlchemy function for query.count() is pretty
      slow. Alternatively, use this optimized function instead.