-->

Sqlalchemy 使用 in or notin 无法批量删除数据

2019-09-11 17:29发布

Sqlalchemy 使用 in or notin 无法批量删除数据

文章目录

      • Sqlalchemy 使用 in or notin 无法批量删除数据
        • 1. 解决方法
        • 2. 场景
        • 3. delete的基本用法

1. 解决方法

可以在delete()括号内添加 synchronize_session=False 或者 synchronize_session=‘fetch’ 实现删除

delete(synchronize_session=False)

2. 场景

当我们使用 in 或者 notin 筛选出需要删除的数据并进行删的时候

def _delete_student(students_id_list):
    """
    :param: student_id_list: 学生身份id列表  
    """
    try:
        self.session.query(students)\
        .filter(students.students_id.in_(students_id_list)).delete()
    except Exception as e:
        print('Delete students Error: %s' % e)

或者

def _delete_student(students_id_list):
    """
    :param: student_id_list: 学生身份id列表  
    """
    try:
        self.session.query(students, s_class).join(s_class)\
        .filter(students.students_id.in_(students_id_list)).delete()
    except Exception as e:
        print('Delete students Error: %s' % e)

通常会出现以下错误:

sqlalchemy.exc.InvalidRequestError: Could not evaluate current criteria in Python. Specify ‘fetch’ or False for the synchronize_session parameter

3. delete的基本用法

delete(delete(synchronize_session='evaluate))
synchronize_session=False : 该参数不会同步删除数据,而是在session结束前删除数据
synchronize_session=‘evaluate’ : 该参数会先评估查询删除的可执行性,如果无法执行就会报错,不支持in or notin
synchronize_session=‘fetch’ : 该参数会将会先查找一次对象,然后在将对象移除session并删除

注:当使用 join 的时候,由于delete当前无法解析关联查询,所以当前无法使用 join 多表查询并删除
update() 方法也是一样

这是因为delete(synchronize_session='evaluate) 的默认参数为synchronize_session='evaluate, 会评估session 的可执行性

def _delete_student(students_id_list):
    """
    :param: student_id_list: 学生身份id列表  
    """
    try:
        self.session.query(students).filter(students.students_id=1).delete()
    except Exception as e:
        print('Delete students Error: %s' % e)

参考:
https://stackoverflow.com/questions/7892618/sqlalchemy-delete-subquery
https://docs.sqlalchemy.org/en/13/orm/query.html?highlight=delete#sqlalchemy.orm.query.Query.delete

标签: