Search code examples
flask-sqlalchemypython-3.6flask-admin

Flask-Admin: add filters on Primary keys


I am trying to add filter on primary keys, that's not working. I went through the source code to find that, it has been excluded: flask-admin/flask_admin/contrib/sqla/view.py

def scaffold_filters(self, name):
    ...
    if column.foreign_keys or column.primary_key:
        continue
    ...

Is there any workaround to this? I tried using the inbuilt filters on pk but it didn't worked.

from back.database import Base
class MyView(ModelView):
    def __init__(self, model):
        self.column_filters = [FilterEqual('_id', '_id')]
        super().__init__(model)

class User(Base):
    _id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(50))

Solution

  • you can just use the column_filters attribute of the ModelView Class

    if you only want the EqualFilter it would look like this:

    class MyView(ModelView):
       column_filters = (FilterEqual(column=User._id, name='id'),)
       def __init__(self, model):
           super().__init__(model)
    

    You can also tell flask_admin to detect all possible filters, then it would look like this

    class MyView(ModelView):
       column_filters = ('_id',)
       def __init__(self, model):
           super().__init__(model)