Flask-SQLAlchemy自引用查询:社交应用粉丝与未关注用户获取方法
问题核心说明
你目前定义的friendship关联表有明确的存储语义:每一行记录代表「user_id对应用户 关注了 friend_id对应用户」。之前查询粉丝列表得不到正确结果的核心原因是直接查询关联表,拿到的是仅含两个外键ID的纯元组,不是带昵称、头像等业务字段的完整User对象,无法直接用于页面渲染或业务逻辑判断。
具体功能实现
1. 获取当前用户的粉丝列表
方式1:模型层加反向只读关联(推荐,和现有代码风格统一)
直接在User类定义中补充粉丝关联,因为这个关系仅用于读取数据,不需要承担写入逻辑,记得配置viewonly=True避免双向写入造成的数据不一致,同时和现有posts关联保持一致的lazy='dynamic'配置,支持后续长列表分页、过滤:
class User(UserMixin, db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(120)) posts = db.relationship('Post', backref='author', lazy='dynamic') # 原有friends、follow、unfollow方法保持不变 friends = db.relationship( "User", secondary=friendship, primaryjoin=id == friendship.c.user_id, secondaryjoin=id == friendship.c.friend_id, ) # 新增的粉丝只读关联 followers = db.relationship( "User", secondary=friendship, primaryjoin=id == friendship.c.friend_id, secondaryjoin=id == friendship.c.user_id, viewonly=True, lazy="dynamic" ) def follow(self, friend): if friend not in self.friends: self.friends.append(friend) def unfollow(self, friend): if friend in self.friends: self.friends.remove(friend)
配置完成后,直接通过current_user.followers.all()就能拿到所有关注了当前用户的User对象列表,和当前获取关注列表的用法保持一致,还能直接调用.paginate()方法做长列表分页。
方式2:手写关联查询(不修改模型的场景使用)
如果不想给模型增加额外关联,直接在查询时把关联表和User表关联,取出完整用户信息即可:
# 关联friendship表和User表,过滤出所有关注了当前用户的用户 followers = User.query.join( friendship, User.id == friendship.c.user_id ).filter( friendship.c.friend_id == current_user.id ).all()
2. 获取当前用户尚未关注的用户列表
分两种场景实现:
小数据量场景(平台用户数小于1万)
写法简单直观,先拿到当前用户已关注的用户ID集合,再从全量用户中排除自己、排除已关注用户:
# 取出已关注用户的ID集合 followed_ids = {user.id for user in current_user.friends} # 过滤出可推荐的未关注用户 suggested_users = User.query.filter( User.id != current_user.id, ~User.id.in_(followed_ids) ).all()
大数据量场景(平台用户数大于1万)
不要把所有已关注的用户ID拉到内存中做过滤,直接在数据库层面通过子查询完成全流程过滤,性能提升明显:
# 构造子查询:获取当前用户已关注的所有用户ID followed_subquery = db.session.query(friendship.c.friend_id).filter( friendship.c.user_id == current_user.id ) # 查询排除自己、排除已关注的所有用户 suggested_users = User.query.filter( User.id != current_user.id, ~User.id.in_(followed_subquery) ).all()
日常优化建议
- 给
friendship表的friend_id字段补充索引:目前只有user_id加了索引,查询粉丝的逻辑是按friend_id条件过滤的,没有索引的话数据量上升后查询会明显变慢,修改表定义如下:friendship = db.Table( "friendships", db.Model.metadata, db.Column("user_id", db.Integer, db.ForeignKey("user.id"), index=True), db.Column("friend_id", db.Integer, db.ForeignKey("user.id"), index=True), ) - 所有长列表查询(关注列表、粉丝列表、推荐用户列表)都配置
lazy='dynamic',配合分页方法使用,不要一次性加载全量数据,避免内存占用过高。 - 保持关注关系的写入逻辑只通过
friends关系操作,不要通过followers关系写入数据,否则容易出现逻辑错误:比如A关注B时,B的关注列表凭空出现A的记录,而实际上B并没有关注A。给followers关系加viewonly=True就是为了从模型层面规避这类错误。
内容的提问来源于stack exchange,提问作者con_w
相关产品推荐
相关产品推荐

