【问题标题】:Flask-Admin User Read/Write Settings Per RowFlask-Admin 用户每行读/写设置
【发布时间】:2014-10-01 17:33:35
【问题描述】:

假设我有用户和子用户表,其中一个用户可以有许多子用户。如何只允许登录用户 (current_user) 仅查看属于该用户的子用户? IE。 Subuser.user_id == current_user.id。我知道我可以通过过滤器来做到这一点,但这必须是强制的,而不是可选的。

如果有帮助,我正在使用 SQLAlchemy 后端!

【问题讨论】:

    标签: sql flask sqlalchemy admin


    【解决方案1】:

    在 Flask Admin 中覆盖后端生成的查询非常简单——你可以做一些相当复杂的事情。请记住覆盖以下所有内容 - 尤其是 get_one()。

    class BaseModelView(ModelView):
        def is_accessible(self):
            # if not authenticated we can't see this
            if not login.current_user.is_authenticated():
                return False
    
            return True
    
        def get_query(self):
            return query.filter(self.model.parent_user_id.any(id=login.current_user.id))
    
        def get_count_query(self):
            # faster count query!
            query = self.session.query(func.count('*')).select_from(self.model).filter(self.model.location_id == login.current_user.id)
    
            return query
    
        def get_one(self, id):
            """
                Return a single model by its id.
    
                :param id:
                    Model id
            """
            result = self.session.query(self.model).get(iterdecode(id))
    
            # if the users location does not exist and she is only allowed to edit locations they control
            if login.current_user.id != result.parent_user_id:
                app.logger.warn('You are not allowed to edit entries for this user.')
                abort(404)
    
            return result
    

    【讨论】:

    • 这对我有用:def get_query(self): return session.query(Login).filter(Login.id == login.current_user.id)
    • 还有:def get_count_query(self): return session.query(func.count(Login)).filter(Login.id == login.current_user.id) 你必须from sqlalchemy import func
    猜你喜欢
    • 2017-05-28
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多