Flask-admin 不强制执行外键约束

Flask-admin not Enforcing foreign key constraints

我有一个 flask 项目,使用的是 sqlalchemy 独立模式,它不是为 flask 项目编码的(因此只使用纯 SQLAlchemy)

片段

class Drive(Base):
    """
    A drive in an edit station.
    """
    __tablename__ = 'drives'

    id = sqlalchemy.Column(sqlalchemy.Integer,
                           primary_key=True,
                           autoincrement=True
                           )
    name = sqlalchemy.Column(sqlalchemy.String(64))
    computer_id = sqlalchemy.Column(sqlalchemy.Integer,
                                    sqlalchemy.ForeignKey(Computer.id)
                                    )
    computer = relationship('Computer', backref='drives')
    # .......... more attr
    current_workgroup_id = sqlalchemy.Column(sqlalchemy.Integer,
                                             sqlalchemy.ForeignKey(Workgroup.id),
                                             nullable=False
                                             )
    workgroup = relationship('Workgroup', backref='drives')


class Workgroup(Base):
    """
    A workgroup.
    """
    __tablename__ = 'workgroups'
    id = sqlalchemy.Column(sqlalchemy.Integer,

                           primary_key=True,
                           autoincrement=True
                           )
    name = sqlalchemy.Column(sqlalchemy.String(16))
    shorthand = sqlalchemy.Column(sqlalchemy.String(4))

数据库架构在 MySQL 中运行良好。如果我有一个带工作组的驱动器,我不能删除该工作组

然而,当使用 flask-admin 时,它没有这样的强制执行。我删除了 workgroup 记录,drive.workgroup 更新为空值。我不确定如何让 Flask-Admin 模块强制执行参照完整性,

AdminViews

class DriveAdmin(sqla.ModelView):
    column_auto_select_related = True
    column_display_pk = True
    column_hide_backrefs = False
    column_display_all_relations = True
    column_searchable_list = ('computer.name', 'name', 'workgroup.name')
    #form_columns = ['computer', 'name', 'workgroup', 'is_active']
    column_list = ('computer', 'name', 'workgroup', 'computer.short_description', 'computer.notes',
                   'computer.station_type.description', 'computer.room.name', 'is_active')


class WorkgroupAdmin(sqla.ModelView):
    column_auto_select_related = True
    column_display_pk = True # optional, but I like to see the IDs in the list
    column_hide_backrefs = True
    column_list = ('id', 'name', 'shorthand')

添加视图

admin = Admin(app, name='Admin Section', template_mode='bootstrap3')
temp_session = EditSession(bind=edit_engine)

admin.add_view(my_admin.ComputerAdmin(Computer, temp_session))
admin.add_view(my_admin.DriveAdmin(Drive, temp_session))
admin.add_view(my_admin.RoomAdmin(Room, temp_session))
admin.add_view(my_admin.WorkgroupAdmin(Workgroup, temp_session))

大部分 column_* = True/False 都是我想弄明白的 -_-

编辑:我不是在寻找 can_delete 设置。我想真正加强完整性,只要没有任何链接,他们仍然可以删除它

好像

workgroup = relationship('Workgroup', backref='drives')

是问题所在。似乎 backref 导致此 table 被视为父级 class,导致多对多关系,其中我想要多对一关系。将行更新为

workgroup = relationship('Workgroup')

似乎支持了预期的完整性