How can I filter a column in the edit form with Fl

2019-05-30 19:58发布

问题:

I am using a model view with flask-admin and I want to filter a column in the edit/create view. The column/field is a relationship and I only want to show fields that belong to the logged in user i.e. relationship_id == user.id

回答1:

Actually I found a easier way for that as below, seems there's no need to override the edit_form method in ModelView, just pass the filtering function as a named parameter(query_factory) to the form_args, and it works like a charming!.

class CustomModelView(ModelView):
    form_args = dict(
        status = dict(label='Status', query_factory=filtering_function)
    )

def filtering_function():
   return app.db.query(CustomModel).filter_by(field_to_filter=my_criteria)


回答2:

I was able to figure this out. Hope the code below helps. It's working pretty well for me.

Below is a rough idea of the code:

class CustomModelView(ModelView):
    def edit_form(self, obj):
        return CustomModelForm(obj=obj)

def filtering_function():
   return app.db.query(CustomModel).filter_by(field_to_filter=my_criteria)

#from wtforms.form import Form
class CustomModelForm(Form):
    field_to_filter = QuerySelectField(query_factory=filtering_function)