Ошибка возникающая при удалении значения в SQLAlchemy.
Ошибка
Основное описание ошибки:
sqlalchemy.orm.exc.StaleDataError: DELETE statement on table ‘…’ expected to delete 1 row(s); Only 0 were matched.
Дерево ошибки:
Traceback (most recent call last):
File «venv/lib/python3.8/site-packages/flask/app.py», line 2464, in __call__
return self.wsgi_app(environ, start_response)
File «venv/lib/python3.8/site-packages/flask/app.py», line 2450, in wsgi_app
response = self.handle_exception(e)
File «venv/lib/python3.8/site-packages/flask/app.py», line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File «venv/lib/python3.8/site-packages/flask/_compat.py», line 39, in reraise
raise value
File «venv/lib/python3.8/site-packages/flask/app.py», line 2447, in wsgi_app
response = self.full_dispatch_request()
File «venv/lib/python3.8/site-packages/flask/app.py», line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File «venv/lib/python3.8/site-packages/flask/app.py», line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File «venv/lib/python3.8/site-packages/flask/_compat.py», line 39, in reraise
raise value
File «venv/lib/python3.8/site-packages/flask/app.py», line 1950, in full_dispatch_request
rv = self.dispatch_request()
File «venv/lib/python3.8/site-packages/flask/app.py», line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File «venv/lib/python3.8/site-packages/flask_login/utils.py», line 272, in decorated_view
return func(*args, **kwargs)
File «app/routes/main.py», line 125, in delete_task
db.session.flush()
File «venv/lib/python3.8/site-packages/sqlalchemy/orm/scoping.py», line 163, in do
return getattr(self.registry(), name)(*args, **kwargs)
File «venv/lib/python3.8/site-packages/sqlalchemy/orm/session.py», line 2536, in flush
self._flush(objects)
File «venv/lib/python3.8/site-packages/sqlalchemy/orm/session.py», line 2678, in _flush
transaction.rollback(_capture_exception=True)
File «venv/lib/python3.8/site-packages/sqlalchemy/util/langhelpers.py», line 68, in __exit__
compat.raise_(
File «venv/lib/python3.8/site-packages/sqlalchemy/util/compat.py», line 182, in raise_
raise exception
File «venv/lib/python3.8/site-packages/sqlalchemy/orm/session.py», line 2638, in _flush
flush_context.execute()
File «venv/lib/python3.8/site-packages/sqlalchemy/orm/unitofwork.py», line 422, in execute
rec.execute(self)
File «venv/lib/python3.8/site-packages/sqlalchemy/orm/unitofwork.py», line 538, in execute
self.dependency_processor.process_deletes(uow, states)
File «venv/lib/python3.8/site-packages/sqlalchemy/orm/dependency.py», line 1104, in process_deletes
self._run_crud(
File «venv/lib/python3.8/site-packages/sqlalchemy/orm/dependency.py», line 1201, in _run_crud
raise exc.StaleDataError(
sqlalchemy.orm.exc.StaleDataError: DELETE statement on table ‘…’ expected to delete 1 row(s); Only 0 were matched.
Решение
Такое возникает из-за пересекающихся отношений в описанных моделях.
Пример, где возникнет ошибка:
__tablename__ = 'task'
id = db.Column(db.Integer(), primary_key=True, unique=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
name = db.Column(db.String(255))
# Для получения доступа к связанным объектам
cats = db.relationship(
'Category',
secondary=categories_task,
backref=db.backref('task', lazy='dynamic')
)
class Category(db.Model, RoleMixin):
__tablename__ = 'categories'
id = db.Column(db.Integer(), primary_key=True, unique=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
name = db.Column(db.String(255))
# Для получения доступа к связанным объектам
tasks = db.relationship(
'Task',
secondary=categories_task,
backref=db.backref('categories', lazy='dynamic')
)
Пересекающиеся отношения приводят к конфликту. Для решения — удалить один из блоков:
tasks = db.relationship