简体   繁体   English

SQLAlchemy:按计数顺序查询

[英]SQLAlchemy: Order query by count

I want to order the query result by the number of likes a post has received. 我想按帖子收到的点赞次数排序查询结果。 This is my Table: 这是我的桌子:

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))

This is the query: 这是查询:

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

The order_by part in SQL, which seems quite right to me: 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

But when I'm calling this after the query: 但是当我在查询后调用此命令时:

for card in cards:
    print card.likes

The output is not in descending but completely random order. 输出不是降序而是完全随机的。 My only guess now is that because of the filter, the count is only executed at those cards with card.user_id == current_user.id. 我现在唯一的猜测是,由于使用了过滤器,计数仅在那些具有card.user_id == current_user.id的卡上执行。 If so (?), how do I order my query result by the total number of likes a post has received? 如果是(?),如何按帖子收到的点赞总数排序查询结果?

Things I looked up before: Hybrid Attributes 1 , SQLAlchemy order by hybrid property 2 , 我之前查询过的内容:混合属性1 ,按混合属性2的 SQLAlchemy顺序,

Thank you. 谢谢。

To be honest I don't see how your sql statement even works, below is the reference to postgresql order by. 老实说,我什至看不到您的sql语句如何工作,以下是对postgresql order by的引用。

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

And I believe your query should be rewritten like so: 而且我相信您的查询应该这样重写:

SQL: 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

But even then it looks wrong to me, can we see your ERD? 但是即使那样对我来说还是错的,我们可以看到您的ERD吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM