pythonflaskflask-sqlalchemyflask-appbuilder

Where does query.filter code go in a Flask-AppBuilder view?


Lets assume we have the following simple view in Flask-AppBuilder :

class Table_AView(ModelView):
    datamodel = SQLAInterface(Table_A)
    label_columns = {'Field_A':'A'}
    list_columns = ['Field_A']

We want the column listing all the data from Field_A to return all the fields equal to "some text".

Assuming the query below is correct where in our code above would we place this line of code to achieve the desired result?

result = session.query(Table_A).filter_by(Field_A = 'some text').all()

Since the implementation is using Flask-appbuilder the usual solutions applied to flask and sqlalchemy dont seem to be implemented the same way.


Solution

  • After much digging flask-appbuilder uses its own filterclass in order to enable you to filter your views.

    All the classes are referenced here on GitHub: Flask Filter Classes List

    Also note the difference between FilterEqual and FilterEqualFunction here: What is the difference between: FilterEqual and FilterEqualFunction?

    For other customization and the first port of call of Flask-appbuilder go straight to the API Reference where you'll find a couple of examples of the filterclass in action.

    In essence it is extremely simple. In your views.py code within the ModelView class you want to filter simply add:

    base_filters = [['field_column_name', FilterEqual, 'abc']]

    This will only show the lines where the field_column_name variable is equal to abc.

    Hope this helps someone as it took me nearly (sigh) two weeks to figure it out...