Flask-SQLAlchemy: How to delete row from many-to-many secondary table with the user id

Viewed 76

I have these two classes and a (many-to-many) secondary table linking them:

association_table = db.Table('association_table',
    db.Column('project_id',db.Integer, db.ForeignKey('project.id'), primary_key=True),
    db.Column('usr_id',db.Integer, db.ForeignKey('usr.id'), primary_key=True)
)

class Usr(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    full_name = db.Column(db.String(150), unique=True, nullable=False)
    email = db.Column(db.String(150), unique=True, nullable=False)
    password = db.Column(db.String(150), nullable=False)
    projects = db.relationship('Project', secondary=association_table, lazy='subquery', backref=db.backref('usrs', lazy=True))

class Project(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(150), unique=True, nullable=False)
    description = db.Column(db.String(1000))
    creation_date = db.Column(db.DateTime(timezone=True), server_default=func.now())
    status = db.Column(db.Boolean, nullable=False)
    tickets = db.relationship('Ticket')
    owner = db.Column(db.Integer, db.ForeignKey('usr.id'))

I want to remove one user from the association_table with his id (user no longer assigned to the project instance) without removing all the other users. How can I do that using Flask-SQLAlchemy?

Example: how can I convert the following command in flask-sqlalchemy?

DELETE FROM association_table WHERE usr_id = 1;
1 Answers

To delete a user by it's id you must do the following:

user = User.query.get(id)
db.session.delete(user)
db.session.commit()

For more information check out this link: How to delete a record by id in Flask-SQLAlchemy

P.D: Replace User by the name of your table

Related