title: SQLAlchemy ordering by count on a many to many relationship
body: <p>This is a simplified example of my current models <em>(I'm using the <a href="http://packages.python.org/Flask-SQLAlchemy/" rel="noreferrer">Flask SQLAlchemy extension</a>)</em>:</p>
  
  <pre><code>like = db.Table(
      'like',
      db.Column('uid', db.Integer, db.ForeignKey('users.id')),
      db.Column('pid', db.Integer, db.ForeignKey('posts.id'))
  )
  
  class User(db.Model):
      __tablename__ = 'users'
  
      id = db.Column(db.Integer, primary_key = True)
      username = db.Column(db.String(20))
  
  class Post(db.Model):
      __tablename__ = 'posts'
  
      id = db.Column(db.Integer, primary_key = True)
      title = db.Column(db.String(255))
  
      likes = db.relationship(
          'User',
          secondary = like,
          backref = db.backref('likes', lazy = 'dynamic'),
          lazy = 'dynamic'
      )
  </code></pre>
  
  <p>I'm trying to order <code>Post</code>'s by the amount of <em>likes</em> it has.</p>
  
  <p>This is the query I'm basically trying to issue:</p>
  
  <pre><code>SELECT p.*, COUNT(l.`pid`) as `likes`
  FROM `posts` as p
  LEFT JOIN `like` as l
      ON p.`id` = l.`pid`
  GROUP BY p.`id`
  ORDER BY `likes` DESC
  </code></pre>
  
  <p>I just haven't been able to get anything working on the SQLAlchemy side of things.</p>
  
  <p>Thanks for any help anyone can offer.</p>