Skip to content Skip to sidebar Skip to footer

How To Customize Flask Admin Queryselectmultiplefield Choice?

I am using flask_admin to allow admin user to access database, where one-to-many relationship is presented. When editing an entry, I would like the dropdown menu to show only the o

Solution 1:

After hours of try/error and googling, it seems this is almost what I want to do. The problem boils down to the fact that edit_form will not be called when ModelView initiated. Therefore I believe there is no direct way to access the model instance that is being edited. The work around is to overwrite edit_form and hijact the obj variable where the model instance is being passed. This is the code working for me (based on the minimized example)

classManySideObjView(ModelView):

    # model instance is passed to edit_form as objdefedit_form(self, obj):
        return self._filtered(
            super(ManySideObjView, self).edit_form(obj), obj.id
        )

    # save id in self._instance_id and access it from _get_listdef_filtered(self, form, id):
        self._instance_id = id
        form.one_side_objs.query_factory = self._get_list
        return form

    # actual query logicdef_get_list(self):
        id = self._instance_id

        return self.session.query(OneSideObj).filter(
            (OneSideObj.active == False) | (OneSideObj.many_side_obj_id == id)
        )

Solution 2:

You're right that the model instance isn't available in the query_factory, but it's not actually necessary to have a function to pass to that field. You can instead just create a query and pass it directly to the form. This avoids the instance variable and can be done in a single method.

classManySideObjView(ModelView):
    defedit_form(self, obj):
        form = super(ManySideObjView, self).edit_form(obj)

        query = self.session.query(OneSideObj).filter(
                    (OneSideObj.active == False) | (OneSideObj.many_side_obj_id == obj.id))

        form.one_side_objs.query = query
        return form

Post a Comment for "How To Customize Flask Admin Queryselectmultiplefield Choice?"