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)

经过实地验证,效果理想

相关推荐
fengxin_rou3 分钟前
黑马点评项目万字总结:从redis基础到实战应用详解
java·开发语言·分布式·后端·黑马点评
财经资讯数据_灵砚智能8 分钟前
基于全球经济类多源新闻的NLP情感分析与数据可视化(夜间-次晨)2026年5月2日
人工智能·python·信息可视化·自然语言处理·ai编程
skiy13 分钟前
SpringBoot项目中读取resource目录下的文件(六种方法)
spring boot·python·pycharm
2601_9561394215 分钟前
集团品牌全案公司哪家专业
大数据·人工智能·python
ouliten15 分钟前
[Triton笔记1]核心概念
笔记·python·深度学习·triton
清水白石00816 分钟前
生成器不是性能银弹:什么时候该用 `yield` 省内存,什么时候它会拖慢 Python 数据处理吞吐?
开发语言·python·原型模式
李松桃17 分钟前
Python爬虫-实战
爬虫·python
不甘先生18 分钟前
Go context 实战指南:从入门到生产级并发控制(架构师避坑手册)
开发语言·后端·golang
观无25 分钟前
Python读取excel并形成api接口案例
python·pandas·fastapi
alwaysrun30 分钟前
Python之文档自动上传至飞书云盘
python·飞书·uploader·云盘