python-3.xflaskflask-sqlalchemyflask-appbuilder

Flask-AppBuilder equivalent of SQLite WHERE clause to filter column data


I'm new to Flask and have started designing a front end for an inventory management database using Flask-AppBuilder.

I have created several models and have have managed to display my sqlite data in tables using Flask-AppBuilder's views.

However, I don't seem to be able to find the equivalent of SQLite WHERE clause to filter or "restrict" column data. I've been reading a lot about sqlalchemy, filters, queries but this has left me more confused that anything else and the explanations seem to be extremely elaborate and complicated to do something which is extremely simple.

Assuming we reproduce the following SQLite query in Flask-AppBuilder:

SELECT Field_A
FROM Table_A
WHERE Field_A = 'some text'

with:

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

Where does the above line of code go in my app?

Considering I have the following Class:

class Table_A(Model):
    id = Column(Integer, primary_key=True)
    Field_A =  Column(String)

    def __repr__(self):
        return self

and View:

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

Solution

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

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

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

    For other customisation and 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_A', FilterEqual, 'abc']] like so:

    `class Table_AView(ModelView):
        datamodel = SQLAInterface(Table_AView)
        label_columns = {'Field_A':'A'}
        list_columns = ['Field_A']
        base_filters = [['field_A', FilterEqual, 'abc']]`
    

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

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