Forked from riteshreddyr/flask-admin many-to-many search.md
Created
September 2, 2016 13:31
-
-
Save 8dspaces/a3ed6c5069a7801dccc6856d975ad574 to your computer and use it in GitHub Desktop.
Flask-admin Many-to-Many Search and Filtering
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #Setting up Flask-admin with SQLAlchemy to be able to search through many-to-many relationships | |
| Many-to-Many searches are not easily supported by Flask-admin. [Read Here for more info ](http://codeseekah.com/2013/08/04/flask-admin-hacks-for-many-to-many-relationships/) | |
| In order to allow for the many-to-many search/filtering support, the association tables need to be added to the list of join tables and then the order of these tables reversed. | |
| Tested on Flask-Admin 1.1.0 | |
| ``` | |
| class Post( Base ): | |
| __tablename__ = 'posts' | |
| id = Column( Integer, primary_key=True ) | |
| title = Column( Unicode( 255 ), nullable=False ) | |
| tags = relationship( 'Tag', backref='posts', secondary='taxonomy' ) | |
| class Tag( Base ): | |
| __tablename__ = 'tags' | |
| id = Column( Integer, primary_key=True ) | |
| name = Column( Unicode( 255 ), nullable=False ) | |
| taxonomy = Table( | |
| 'taxonomy', Base.metadata, | |
| Column( 'post_id', Integer, ForeignKey( 'posts.id' ) ), | |
| Column( 'tag_id', Integer, ForeignKey( 'tags.id' ) ), | |
| ) | |
| ``` | |
| ``` | |
| class PostModelView( ModelView ): | |
| column_searchable_list = ( Post.title, Tag.name ) | |
| column_filters = (Post.title, Tag.name) | |
| def init_search( self ): | |
| r = super( PostModelView, self ).init_search() | |
| #add the association table to search join list | |
| self._search_joins.append(taxonomy) | |
| #reverse the lsit so that the association table appears before the two main tables | |
| self._search_joins.reverse() | |
| return r | |
| def scaffold_filters(self, name): | |
| filters = super( PostModeView, self).scaffold_filters(name) | |
| #Check if "tags" table has been processed and the join table added | |
| if "tags" in self._filter_joins: | |
| #add the association table to the filter join tables | |
| self._filter_joins.append(taxonomy) | |
| #reverse the list so that the association table appears before the two main tables | |
| self._filter_joins.reverse() | |
| return filters | |
| ``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment