python - 获取按时间戳排序的一组用户的所有帖子

标签 python flask sqlalchemy flask-sqlalchemy

我有三个模型:一个 User、一个 Post 和一个 Follow,它们记录一个用户何时关注了另一个用户。我想显示当前用户关注的用户的所有帖子。帖子列表应按时间戳排序。但是,该列表似乎按用户 ID 分组,然后按时间戳排序。如何获取仅按时间戳排序的关注用户的所有帖子?

followed_users = Follow.query.filter_by(follower_id=current_user.id).all()
followed_posts = []
for i in followed_users:
    followed_posts.extend(Post.query.filter(Post.author == i.followed_id).order_by(Post.timestamp.desc()).all())

最佳答案

您查询了所有用户,然后针对每个用户查询了他们按时间戳排序的帖子。最终结果是按时间戳排序的帖子列表,按用户分组。相反,查询任何用户的所有帖子。将对所有后续 ID 的查询传递给对任何这些 ID 的任何帖子的查询。

followed_ids = db.session.query(Follow.followed_id).filter(Follow.follower_id == current_user.id).subquery()
followed_posts = Post.query.filter(Post.author.in_(followed_ids)).order_by(Post.timestamp.desc()).all()

关于python - 获取按时间戳排序的一组用户的所有帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32318007/

相关文章:

sqlalchemy - 在查询中查找 Table 对象

python - SQLAlchemy 快速搜索

python - 命令在 CMD 中有效,但在子进程中无效

python - SimpleXMLRPCServer 不支持方法签名?

python - Virtualenv 包含全局包/如何清除我的 PYTHONPATH?

python - 带有跳转主机和远程数据库的SSH隧道转发

python - 使用python将pyspark数据框中的多列合并为一列

javascript - jinja2.exceptions.TemplateSyntaxError : expected token ',' , 得到 'static'

python - 保存时格式化会删除 VS-Code 中的导入语句

python - Flask APScheduler - Cron Job 只发生在页面上的活跃用户身上