如何使用关系从 sqlalchemy 中的关联 table 中删除映射的子项

How to delete mapped children from associations table in sqlalchemy using relationships

文档说:

Mapping a one-to-many or many-to-many relationship results in a collection of values accessible through an attribute on the parent instance. By default, this collection is a list

所以我有角色用户,我可以使用 user.roles 和 user.roles.append() 方法访问它,但我无法删除所有映射条目。 我试过了:

 user.roles = []

我也尝试了 clear() 方法和循环中的 remove() 但我总是得到

    sqlalchemy.orm.exc.FlushError: Can't flush None value found in collection Users.roles

这是我的表关系示例

 class Users(sa.Model):
__tablename__ = 'users'

id = Column(Integer, primary_key=True, autoincrement=True)
login = Column(String(50), unique=False)

roles = relationship('Roles', secondary='user_roles_map',
                     cascade='all, delete')


class Roles(sa.Model):
__tablename__ = 'roles'

id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(String(40), unique=True)



class UserRolesMap(sa.Model):
__tablename__ = 'user_roles_map'

id_seq = Sequence(__tablename__ + "_id_seq")
id = Column(Integer(), id_seq, server_default=id_seq.next_value(),
            unique=True, nullable=False)
user_id = Column(
    Integer, ForeignKey('users.id'),
    primary_key=True)
role_id = Column(
    Integer, ForeignKey('roles.id'),
    primary_key=True)

是否可以通过访问父条目的角色属性来删除所有条目?

在 user.roles = []

之后需要调用 flush()