I have a flask app that uses a blend of sqlalchemy (ORM) and flask sqlalchemy.
I have a User model, a Post model, and a followers table as follows:
from app import db
from flask_login import UserMixin
from sqlalchemy.orm import relationship
class User(UserMixin, db.Model)
id = db.Column(db.Integer, primary_key=True)
followed = db.relationship('User', secondary=followers,
primaryjoin=(followers.c.follower_id == id),
secondaryjoin=(followers.c.followed_id == id),
backref=db.backref('followers', lazy='dynamic'), lazy='dynamic') # many to many relationship with other Users
posts = relationship('Post') # one to many relationship with posts
# ...
class Post(db.Model)
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
#...
followers= db.Table('followers',
db.Column('follower_id', db.Integer, db.ForeignKey('user.id')),
db.Column('followed_id', db.Integer, db.ForeignKey('user.id'))
)
My question is how to query the Post table/model so that it returns only posts written by users that follow you back (i.e. friends).
The flask mega tutorial by Miguel Grinberg (which these models are based off of) uses the following sqlalchemy query to accomplish something similar to what I'm after.
def followed_posts(self):
return Post.query.join(
followers, (followers.c.followed_id == Post.user_id)).filter(
followers.c.follower_id == self.id).order_by(
Post.timestamp.desc())
I've been trying to modify the above query so that the Post table joins only with the subset of followers, characterized by if (a,b) in followers, then (b,a) in followers. I am just not sure how to implement this.
Any help would be appreciated. Also if anyone has a recommendation for a guide that goes over more 'advanced' sqlalchemy queries like the one above without a ton of pure SQL prerequisite knowledge please let me know. Thanks in advance!
followed_id
andfollower_id
in thedef followed_posts(self): ...
query from Miguels's case: he lists the posts of those you follows, so the inverse will be the posts of those who follow you. – van