title: SQLAlchemy: filtering count in many-to-many relationship query
body: <p>In my Flask app, there is a many-to-many relationship between Documents and Tokens:</p>
  
  <pre><code>DocTokens = db.Table(
      'DocTokens',
      db.Column('token_id', db.Integer, db.ForeignKey('Token.id')),
      db.Column('document_id', db.Integer, db.ForeignKey('Document.id')),
      )
  
  class Token(db.Model):
      __tablename__ = 'Token'
      id = db.Column(db.Integer, primary_key=True)
      ...
      is_gold = db.Column(db.Boolean, default=None)
  
  class Document(db.Model):
      __tablename__ = 'Document'
      id = db.Column(db.Integer, primary_key=True)
      ...
      tokens = db.relationship(
          'Token',
          secondary=DocTokens,
          backred=db.backref('documents', lazy='dynamic'),
          )
  </code></pre>
  
  <p>I'd like to construct a <strong>Document query</strong>, ordered (descendingly) by the number of related Tokens <em>where Token.is_gold is None</em>.</p>
  
  <p>So far, I've figured out how to order Documents by the number of related Tokens:</p>
  
  <pre><code>db.session.query(
      Document,
      func.count(DocTokens.c.token_id).label('total')
      ).join(DocTokens).group_by(Document).order_by('total DESC')
  </code></pre>
  
  <p>But, I can't seem to make that count include only Tokens where Token.is_gold is None. Here is one of many failed attempts:</p>
  
  <pre><code>db.session.query(
      Document,
      func.count(DocTokens.c.token_id)
      .filter(Token.is_gold.is_(None)).label('total')
      ).join(DocTokens).group_by(Document).order_by('total DESC')
  </code></pre>
  
  <p>It threw the following error:</p>
  
  <pre><code>AttributeError: Neither 'count' object nor 'Comparator' object has an attribute 'filter'
  </code></pre>
  
  <p>Here are some of the StackOverflow solutions I've tried to model (incl. solutions involving subqueries and hybrid properties):</p>
  
  <ul>
  <li><a href="https://stackoverflow.com/questions/22876946/how-to-order-by-count-of-many-to-many-relationship-in-sqlalchemy">How to order by count of many-to-many relationship in SQLAlchemy?</a></li>
  <li><a href="https://stackoverflow.com/questions/24565211/sort-by-count-of-many-to-many-relationship-sqlalchemy">Sort by Count of Many to Many Relationship - SQLAlchemy</a></li>
  <li><a href="https://stackoverflow.com/questions/25142511/order-by-a-method-contained-within-a-class-in-sqlalchemy">SQLAlchemy ordering by count on a many to many relationship</a></li>
  <li><a href="https://stackoverflow.com/questions/25142511/order-by-a-method-contained-within-a-class-in-sqlalchemy">order by a method contained within a class in SQLAlchemy</a></li>
  </ul>
  
  <p>I'm fairly new to SQL/SQLAlchemy... Any help is greatly appreciated!</p>