SQLAlchemy:按计数排序查询

时间:2016-05-23 23:08:04

标签: python sql postgresql flask sqlalchemy

我想按照收到的帖子的数量来查询查询结果。 这是我的表:

class Card(Base):
   __tablename__ = 'cards'
   id = Column(Integer, primary_key=True)
   post_id = Column(Integer)
   voted = Column(Boolean)

@hybrid_property
def likes(self):
   likes = session.query(Card).filter(and_(Card.post_id == self.post_id, Card.voted == True)).count()
   return likes

@likes.expression
def likes(cls):
   return (select([func.count(Card.id)]).where(and_(Card.post_id == cls.post_id, Card.voted == True))

这是查询:

cards = session.query(Card).filter(Card.user_id == current_user.get_id()).order_by(desc(Card.likes)).all()

SQL中的order_by部分,对我来说似乎很合适:

ORDER BY (SELECT count(cards.id) AS count_1 FROM cards WHERE cards.post_id = cards.post_id AND cards.voted = true) DESC

但是当我在查询后调用它时:

for card in cards:
    print card.likes

输出不是降序,而是完全随机的顺序。我现在唯一的猜测是,由于过滤器,计数只在card.user_id == current_user.id的卡上执行。如果是这样(?),我如何按照帖子收到的总数来订购我的查询结果?

之前我查过的内容:混合属性1,SQLAlchemy按混合属性排序2

谢谢。

1 个答案:

答案 0 :(得分:-1)

老实说,我看不出你的sql语句是如何工作的,下面是对postgresql命令的引用。

http://www.postgresql.org/docs/9.4/static/queries-order.html http://www.tutorialspoint.com/postgresql/postgresql_having_clause.htm

我相信你的查询应该像这样重写:

SQL:

SELECT count(cards.id) AS count_1, cards.id
FROM cards
GROUP BY count_1
HAVING cards.voted = true
ORDER BY count_1 DESC

但即使这样,我看起来也不对,我们能看到你的ERD吗?