无法让关联表为特定用户急切加载电影,以显示添加电影的用户是否正在被关注 Flask

问题描述

class Movie(db.Model):
    __searchable__ = ['genre']
    id = db.Column(db.Integer,primary_key=True)
    name = db.Column(db.String(200))
    timestamp = db.Column(db.DateTime,index=True,default=datetime.utcNow)
    user_id = db.Column(db.Integer,db.ForeignKey('user.id'))
    username = db.Column(db.String(255))
    description = db.Column(db.String(100))


class User(db.Model,UserMixin):

    __tablename__ = 'user'

    id = db.Column(db.Integer,primary_key=True)
    username = db.Column(db.String(64),unique=True)
    email = db.Column(db.String,nullable=False)
    password = db.Column(db.String,nullable=False)
    movies = db.relationship('Movie',backref='author',lazy='joined')
    followed = db.relationship('User',secondary=followers,primaryjoin=(followers.c.follower_id==id),secondaryjoin=(followers.c.followed_id==id),backref=db.backref('followers',lazy='joined'),lazy='joined')

followers = db.Table('followers',db.Column('follower_id',db.Integer,db.ForeignKey('user.id'),primary_key = True),db.Column('followed_id',primary_key = True) )

def get_all_movies_follow():
    
    qry = Movie.query.order_by(Movie.id.desc()).all()

    movies_schema = MovieSchema(many=True)

    return movies_schema.dump(qry)

    

如何取回我有一个属性的集合(数组),该属性显示是否 当我eager_load follower 表时,它仍然不会出现在查询中。 ``` #movi = Movie.query.outerjoin(followers,follower.c.followed_id == Movie.user_id).options(contains_eager(Movie.us).contains_eager('followers')).order_by(Movie.id.desc ()).all()

Also when I try to use follow unfollow function I get Select statement 'SELECT *
FROM followers,movie AS movie_1
WHERE followers.followed_id = movie_1.user_id' returned no FROM clauses due to auto-correlation; specify correlate(<tables>) to control correlation manually.

which in short is def unfollow(id):
...         
    current_user.unfollow(user)
    db.session.commit()

def follow(self,user):
        if not self.is_following(user):
            self.followed.append(user)
    def unfollow(self,user):
        if self.is_following(user):
            self.followed.remove(user)

    def is_following(self,user):
        return self.query.filter(followers.c.followed_id==user.id).count()>0


So I tried adding this to Movie class:  ```following = column_property( exists().where(followers.c.followed_id==user_id)) but it has to be also restricted on current_user.id=followers.c.follower_id

我在想可能会在我查询电影时包含的语句

解决方法

好的,所以这行得通,当然我在架构中包含以下内容以转储到 MovieSchema 上。 但它有一个问题。如果 (followers.c.follower_id) 没有匹配项,则用户不会关注任何人。然后我得到一个空结果并且根本没有加载任何电影。

class Movie(db.Model)
...
following = column_property( exists().where(followers.c.followed_id==user_id).correlate_except(followers))

and in query
qry = db.session.query(Movie).filter(followers.c.follower_id == current_user.id).all()