Flask-admin not执行外键约束

时间:2015-11-17 13:54:26

标签: python mysql flask sqlalchemy flask-admin

我有一个烧瓶项目,使用sqlalchemy独立架构,没有为烧瓶项目编码(因此只使用纯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中运行良好。如果我有一个包含工作组的云端硬盘,则无法删除该工作组enter image description here

但是,使用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')

addviews

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设置。我想真正强制执行诚信,因为他们仍然可以删除它,只要没有任何关联

1 个答案:

答案 0 :(得分:0)

看起来好像是

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

是问题线。似乎backref导致该表被视为父类,导致多对多关系,其中我想要多对一关系。将行更新为

workgroup = relationship('Workgroup')

似乎已按预期支持完整性