Francesco Della Vedova
Francesco Della Vedova

Reputation: 943

Flask-Admin: add filters on foreign keys

I am using Flask-Admin to create a back-end interface for my application. I want to add some filters in an Admin View, but I get this error:

'Exception: Unsupported filter type column_name'

Where column name is a column field that is a Foreign Key.

Here are the models:

class Keywords(Base):
    id = Column(String(4), primary_key=True)
    language = Column(ForeignKey('w_accounts.language'))
    camp_type = Column(ForeignKey('w_camp_types.camp_type'))
class KeywordsAdmin(BaseAdmin):
   column_searchable_list = ('toa_id', 'name', 'toa')
   column_list = ('toa_id', 'language', 'camp_type', 'name', 'aliases', 'toa', 'toa_type')
   column_filters = ('language',) 

After going through the API, I tried to add the following attribute as well:

       column_select_related_list = ('language',)

Instead of getting an error immediately, I get an exception when I load the page on the browser,

"AttributeError: 'ColumnProperty' object has no attribute 'mapper'"

Upvotes: 3

Views: 3777

Answers (1)

swietyy
swietyy

Reputation: 834

You have to add relationship.

class Keywords(Base):
    id = Column(String(4), primary_key=True)
    language = Column(ForeignKey('w_accounts.language'))
    camp_type = Column(ForeignKey('w_camp_types.camp_type'))

    language_ref = relationship("w_accounts", backref=db.backref('keywords', lazy='dynamic'))

And then:

column_select_related_list = ('language_ref',)

Upvotes: 2

Related Questions