title: Flask SQLAlchemy - How to order query result by count of ForeignKey variable
body: <p>I'm implementing blog posts type Flask app using Flask-SQLAlchemy. </p>
  
  <p>I'm trying to order the blog posts based on total number of likes each blog post received. I've tried using SQLALchemy hybrid property with query <code>session.query(Post).order_by(Post.likes_count.desc()).all()</code> which is similar to solution to a question asked earlier <a href="https://stackoverflow.com/questions/27521645/sqlalchemy-order-by-function-result">here</a></p>
  
  <p>It throws error <code>AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with Post.likes has an attribute 'count'</code></p>
  
  <p>Is there a way to get posts order using likes count which needs to be fed to paginate function.</p>
  
  <pre><code>class User(db.Model, UserMixin):
      id = db.Column(db.Integer, primary_key=True)
      username = db.Column(db.String(20))
      email = db.Column(db.String(120))
      likes = db.relationship('Like', backref='user',lazy='dynamic',foreign_keys='Like.user_id')
      def __repr__(self):
          return f"User('{self.username}', '{self.email}')"
  
  class Post(db.Model):
      id = db.Column(db.Integer, primary_key=True)
      title = db.Column(db.String(100))
      date_posted = db.Column(db.DateTime, default=datetime.utcnow)
      user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
      likes = db.relationship('Like', backref='post', lazy='dynamic')
  
      @hybrid_property
      def likes_count(self):
          return self.likes.count()
  
      def __repr__(self):
          return f"Post('{self.title}', '{self.date_posted}')"
  
  class Like(db.Model):
      id = db.Column(db.Integer, primary_key=True)
      user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
      post_id = db.Column(db.Integer, db.ForeignKey('post.id'))
  </code></pre>
  
  <p>This question is similar to <a href="https://stackoverflow.com/questions/22876946/how-to-order-by-count-of-many-to-many-relationship-in-sqlalchemy?rq=1">How to order by count of many-to-many relationship in SQLAlchemy?</a> However I was not able to get query results with <code>len</code> or <code>count()</code> method mentioned in answer/comments. </p>