Исправляем ошибку в SQLAlchemy при удалении данных: sqlalchemy.orm.exc.StaleDataError.
Ошибка:
raise orm_exc.StaleDataError(
sqlalchemy.orm.exc.StaleDataError: UPDATE statement on table ‘categories’ expected to update 4 row(s); 0 were matched.
Возникает при пересекающихся db.relationship. Когда связи указаны в моделях друг друга. Например:
class Task(db.Model, RoleMixin):
__tablename__ = 'task'
cats = db.relationship(
'Category',
secondary='categories_task',
backref=db.backref('task'),
)
__tablename__ = 'task'
cats = db.relationship(
'Category',
secondary='categories_task',
backref=db.backref('task'),
)
и
class CategoriesDone(db.Model):
__tablename__ = 'categories_task'
id = db.Column(db.Integer(), primary_key=True, unique=True)
done_id = db.Column(db.Integer, db.ForeignKey('task.id'))
cat_id = db.Column(db.Integer, db.ForeignKey('categories.id'))
time_passed = db.Column(db.Integer())
time = db.Column(db.DateTime())
done = db.relationship(Done, backref="categories_task")
cat = db.relationship(Category, backref="categories_task")
__tablename__ = 'categories_task'
id = db.Column(db.Integer(), primary_key=True, unique=True)
done_id = db.Column(db.Integer, db.ForeignKey('task.id'))
cat_id = db.Column(db.Integer, db.ForeignKey('categories.id'))
time_passed = db.Column(db.Integer())
time = db.Column(db.DateTime())
done = db.relationship(Done, backref="categories_task")
cat = db.relationship(Category, backref="categories_task")
Для решения этой проблемы установить passive_deletes=True, т.е.:
cats = db.relationship(
'Category',
secondary='categories_task',
backref=db.backref('task'),
passive_deletes=True
)
'Category',
secondary='categories_task',
backref=db.backref('task'),
passive_deletes=True
)