flask-admin modelview 中重写get_query函数
背景:
flask-admin框架中提供的模型视图默认是显示表实体中的所有列表数据,如果想通过某种条件限制初始列表数据,那么久需要重写一些方法才能实现。
材料:
略
制作:
视图源码:
def get_query(self):
return super(MyAiConfigView, self).get_query().filter(AiConfig.status == 0)
效果:
1、过滤前
2、过滤后
经验:
1、实现初始化过滤,我们可以想到的和百度上搜到的一定是重写def get_list(self, page, sort_field, sort_desc, search, filters, page_size=20) 来实现,这种方法的确可行,但这样处理不当会破坏原
# def get_list(self, page, sort_field, sort_desc, search, filters, page_size=20):
# query = self.get_query()
# count_query = self.get_count_query() if not self.simple_list_pager else None
# query = query.all()
# return None, query
始的配置项,这一点可以通过源码看出
execute=True, page_size=None):
"""
Return records from the database.
:param page:
Page number
:param sort_column:
Sort column name
:param sort_desc:
Descending or ascending sort
:param search:
Search query
:param execute:
Execute query immediately? Default is `True`
:param filters:
List of filter tuples
:param page_size:
Number of results. Defaults to ModelView's page_size. Can be
overriden to change the page_size limit. Removing the page_size
limit requires setting page_size to 0 or False.
"""
# Will contain join paths with optional aliased object
joins = {}
count_joins = {}
query = self.get_query()
count_query = self.get_count_query() if not self.simple_list_pager else None
# Ignore eager-loaded relations (prevent unnecessary joins)
# TODO: Separate join detection for query and count query?
if hasattr(query, '_join_entities'):
for entity in query._join_entities:
for table in entity.tables:
joins[table] = None
# Apply search criteria
if self._search_supported and search:
query, count_query, joins, count_joins = self._apply_search(query,
count_query,
joins,
count_joins,
search)
# Apply filters
if filters and self._filters:
query, count_query, joins, count_joins = self._apply_filters(query,
count_query,
joins,
count_joins,
filters)
# Calculate number of rows if necessary
count = count_query.scalar() if count_query else None
# Auto join
for j in self._auto_joins:
query = query.options(joinedload(j))
# Sorting
query, joins = self._apply_sorting(query, joins, sort_column, sort_desc)
# Pagination
query = self._apply_pagination(query, page, page_size)
# Execute if needed
if execute:
query = query.all()
return count, query
2、在源代码学习中发现了本文探讨的新大陆---get_query(self) ,下面是源码中针对该函数的例子
class MyView(ModelView):
def get_query(self):
return super(MyView, self).get_query().filter(User.username == current_user.username)
经过实地验证,效果理想