Search code examples
flaskflask-admin

flask-admin how to access model in viewmodel


I want to access the model in a descendant ModelView like so:

class MyAppLibraryView(MyModelView):
    if model != Salary:
        column_searchable_list = ['name', ]
    form_excluded_columns = ['date_created', 'date_modified', ]
    column_display_pk = True

This class is used as follows:

admin.add_view(MyAppLibraryView(Section, db.session))
admin.add_view(MyAppLibraryView(Office, db.session))
admin.add_view(MyAppLibraryView(Salary_reference, db.session))
admin.add_view(MyAppLibraryView(Salary, db.session))

In MyAppLibraryView, model is unknown to the class. How do I access the models passed to the class MyAppLibraryView?


Solution

  • As you can see in flask-admin code, you can access model with self.model.

    You have some ways to override column_searchable_list based on the model.

    1. Subclass (the way I recommend)
    class MyAppLibraryView(MyModelView):
        form_excluded_columns = ['date_created', 'date_modified', ]
        column_display_pk = True
    
    
    class MyAppLibrarySalaryView(MyAppLibraryView):
        column_searchable_list = ['name', ]
    
    
    admin.add_view(MyAppLibrarySalaryView(Salary, db.session))
    
    1. you can set it in __init__.
    class MyAppLibraryView(MyModelView):
        def __init__(self, model, *args, **kwargs):
            if model != Salary:
                self.column_searchable_list = ['name',]
    ]
            super(MyAppLibraryView, self).__init__(model, *args, **kwargs)