Flask-SQLAlchemy笔记(一):通过query语句获取关注用户的帖子

 一,预先定义内容

#关联表
followers = db.Table('followers', db.Column('follower_id', db.Integer, db.ForeignKey('user.id')), db.Column('followed_id', db.Integer, db.ForeignKey('user.id')) )
Post.query.join(...).filter(...).order_by(...)

二,模型图示

用户表User

idusername
1 john
2 susan
3 mary
4 david

关系表followers(当john关注susan和david时)

follower_idfollowed_id
1 2
1 4
2 3
3 4

 帖子表Post

idtextuser_id
1 post from susan 2
2 post from mary 3
3 post from david 4
4 post from john 1

三,join方法

#join将创建一个临时表根据参数条件组合posts和followers表的数据
#条件为被关注者的id==帖子的id,即按照被关注这的帖子ID进行对应连接
Post.query.join(followers, (followers.c.followed_id == Post.user_id))

join连接结果如下

idtextuser_idfollower_idfollowed_id
1 post from susan 2 1 2
2 post from mary 3 2 3
3 post from david 4 1 4
3 post from david 4 3 4

四,Filter方法

#注意方法定义在用户表里,所以self表示当前用户实例
filter(followers.c.follower_id == self.id)

 Filter进行过滤只保留调用这个方法的用户

例如调用者john过滤后的结果如下

idtextuser_idfollower_idfollowed_id
1 post from susan 2 1 2
3 post from david 4 1 4

五,order_by方法

对最后结果参考发布时间进行降序排列

order_by(Post.timestamp.desc())

最后连接起来即为

Posts=Post.query.join(followers,(followers.c.followed_id==Post.user_id)
        ).filter(followers.c.followed_id==self.id).order_by(Post.timestamp.desc())
可以直接留言交流问题或想法,每天都会看
原文地址:https://www.cnblogs.com/shitianfang/p/12362525.html