简体   繁体   中英

How can I filter a column in the edit form with Flask-Admin ModelView?

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 ie relationship_id == user.id

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM