pallets-eco / flask-admin

Simple and extensible administrative interface framework for Flask
https://flask-admin.readthedocs.io
BSD 3-Clause "New" or "Revised" License
5.79k stars 1.57k forks source link

Filter convertor to custom filter #1936

Open Hayat5 opened 4 years ago

Hayat5 commented 4 years ago

Could I add file convertor to custom filter not related to specific column?

ljluestc commented 5 months ago

from flask_admin.contrib.peewee import ModelView
from flask_admin.model.filters import BaseFilter
from flask_admin.contrib.peewee.filters import FilterEqual
from your_module import YourModel, filtering_fun

class CustomFilter(BaseFilter):
    def __init__(self, name, converter=None):
        super(CustomFilter, self).__init__(name)
        self.converter = converter

    def apply(self, query, value):
        converted_value = self.convert_value(value)
        return self.apply_filter(query, converted_value)

    def apply_filter(self, query, value):
        # Implement your filtering logic here
        pass

    def convert_value(self, value):
        if self.converter:
            return self.converter(value)
        return value

class CustomModelView(ModelView):
    def scaffold_filters(self, name):
        filters = super(CustomModelView, self).scaffold_filters(name)
        if name == 'custom_field':
            filters.append(CustomFilter(name, converter=my_converter_function))
        return filters

admin.add_view(CustomModelView(YourModel))