删除SqlalChemy上的多对多(关联对象)关系

2022-03-10 00:00:00 python sqlalchemy flask flask-sqlalchemy

问题描述

我遇到SqlAlChemy问题。

我只想删除一个关系。此关系由关联对象建立。

型号

class User(db.Model, UserMixin):
    id                  = db.Column(db.Integer, primary_key=True)
    email               = db.Column(db.String(255), unique=True)
    username            = db.Column(db.String(255), unique=True)
    password            = db.Column(db.String(255))
    following           = db.relationship('Follower', foreign_keys='Follower.user_id')
    followed_by         = db.relationship('Follower', foreign_keys='Follower.follow_user_id')

    def __repr__(self):
        return '<%s (%i)>' % (self.username, self.id)

class Follower(db.Model):
    __tablename__       = 'followers'

    user_id             = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True)
    follow_user_id      = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True)
    created_at          = db.Column(db.DateTime, default=datetime.datetime.now)

    user_followed       = db.relationship("User", primaryjoin=(follow_user_id==User.id))
    user                = db.relationship("User", primaryjoin=(user_id==User.id))

    def __repr__(self):
        return '<%i %i>' % (self.user_id, self.follow_user_id)

添加关系的方式(有效!):

u1 = # user 1
u2 = # user 2

...

f = Follower()
f.user_followed = u2
u1.following.append(f)
db.session.commit()

如何尝试删除关系(不起作用):

f = Follower()
f.user_followed = u2

u1.following.remove(f)
db.session.commit()

错误

ValueError: list.remove(x): x not in list

我理解它为什么不能工作,因为这个Follower()实例不在列表u1中。那么,如何删除此关系?


解决方案

用户也可以先尝试查询该对象,然后将其从列表中删除。

follower_to_be_deleted = db.session.query(Follower).filter_by(user_id=u2.id).first()
u1.following.remove(follower_to_be_deleted)
db.session.commit()

相关文章