You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Flask-SQLAlchemy获取热门关注股票代码的关注人数?

解决Flask+SQLAlchemy多对多关联下统计股票关注数的问题

你当前的问题是直接查询所有tickers会返回每个用户关联的股票实例,导致同一股票重复出现。要实现按股票分组统计关注人数,需要用SQLAlchemy的分组聚合查询来处理:

1. 修改视图中的查询语句

替换原来的tickers = Tickers.query.all(),改用聚合查询获取每个股票的关注人数:

from sqlalchemy import func

# 关联中间表,分组统计每个股票的关注用户数,并按关注数降序排列
tickers_with_count = db.session.query(
    Tickers.name,
    func.count(list.users_id).label('followers_count')
).join(list, Tickers.id == list.tickers_id) \
.group_by(Tickers.id, Tickers.name) \
.order_by(func.count(list.users_id).desc()) \
.all()

这里通过join关联中间表list,用func.count统计每个股票对应的用户数量,group_by按股票分组,order_by可以让最受关注的股票排在前面。

2. 修改模板代码

模板中直接遍历查询结果,显示股票名称和对应的关注数:

{% for ticker in tickers_with_count %}
    <li class="list-group-item">{{ ticker.name }}: {{ ticker.followers_count }}</li>
{% endfor %}

补充说明

如果不需要按关注数排序,去掉order_by部分即可。另外也可以在Tickers模型中添加属性来获取关注数,但这种方式会为每个股票单独查询用户列表,数据量大时效率不如聚合查询:

class Tickers(db.Model):
    # 原有字段...
    @property
    def followers_count(self):
        return len(self.users)

内容的提问来源于stack exchange,提问作者Ahmed B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 16:32:49