Filter and Sort on Custom Field in Flask-admin ModelView
Asked Answered
C

1

6

I want to add filters for amount (custom field) in Model View

class FarmerAdmin(ModelView):

    column_descriptions = dict(amount = "All Transactions Total (Rs.)")

    column_searchable_list = ('name','village','phone')

    column_editable_list = ('phone',)

    column_filters = ('village','area',\
                  filters.FloatGreaterFilter('amount','Amount'))

    inline_models = (Transaction,)

    def get_query(self):
        return self.session.query(
            Farmer.id.label("id"),
            Farmer.name.label("name"),
            Farmer.village.label("village"),
            Farmer.phone.label("phone"),
            Farmer.area.label("area"),
            func.sum(Transaction.total).label("amount")
            ).join(Transaction).group_by(Farmer.id)

    def scaffold_sortable_columns(self):
        return {'id':'id','name':'name','village':'village',\
            'area':'area','amount':'amount'}

    def scaffold_list_columns(self):
        return ['id','name','village','phone','area','amount']


    def __init__(self, session):
        super(FarmerAdmin, self).__init__(Farmer, session)

Sort works great by overriding scaffold_sortable_columns method. Is there a way to add standard filters (greater than, less than) for amount column as well.

Crankshaft answered 16/7, 2015 at 14:25 Comment(0)
D
2

I will take greater as an example

from flask_admin.contrib.sqla.filters import FilterGreater

class FarmerAdmin(ModelView):
    FilterGreater(Farmer.amount, u'Amount')

for more information please check http://flask-admin.readthedocs.io/en/latest/_modules/flask_admin/contrib/sqla/filters/

Domineca answered 7/5, 2016 at 13:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.