将当前过滤器选择提供给 Django 中的另一个自定义 SimpleListFilter

2024-04-22

我正在尝试更改一个过滤器的提示,以响应另一个过滤器中所做的当前选择。我非常不知道如何将 AttributeCategoryFilter 的当前选定值传递到 AttributeFilter 中。我正在使用 Django 1.4-dev。试图弄清楚我是否应该使用RelatedFieldListFilter来达到这个目的。看起来这些功能还很年轻,目前还没有任何例子。

    class AttributeCategoryFilter(SimpleListFilter):
        title = _('Attribute Category')
        parameter_name = 'attribute_category'
        def lookups(self, request, model_admin):
            attributes = Attribute.objects.filter(parent_attribute=None)
            prompts = []
            for attribute in attributes:
                prompts.append((attribute.title, _(str(attribute.title))))
            return prompts
        def queryset(self, request, queryset):
            if self.value():
                return queryset.filter(attribute__category=self.value())
            else:
                return queryset


    class AttributeFilter(SimpleListFilter):
        title = _('Attribute Title')
        parameter_name = 'attribute_title'
        def lookups(self, request, model_admin):
            desired_category =  # Needs to be a reference to the selected value in the AttributeCategoryFilter above
            attributes = Attribute.objects.filter(category=desired_category).exclude(parent_attribute=None)
            prompts = []
            for attribute in attributes:
                prompts.append((attribute.title, _(str(attribute.title))))
            return prompts
        def queryset(self, request, queryset):
            if self.value():
                return queryset.filter(attribute__title=self.value())
            else:
                return queryset


    class ValueAdmin(admin.ModelAdmin):
        list_display = ('package', 'attribute', 'presence', 'text', 'modified', 'created')
        list_filter = ('package', AttributeCategoryFilter, AttributeFilter, 'presence', 
            'attribute__admin_approved', 'attribute__dtype', 'modified')
        search_fields = ('package', 'attribute', 'text')
        list_display_links = ('package', )
        list_editable = ('presence', 'text')
        list_per_page = 20000
    admin.site.register(Value, ValueAdmin)   

这对我有用...“TypeListFilter”仅在使用“类别”过滤器后才可见,然后显示属于所选类别“subTypeOf”的所有条目。进一步的“特殊情况”黑客确保当用户选择另一个类别时过滤器消失。 “_class”参数增加了一些额外的灵活性。我将相同的过滤器与不同但相关的 Type 类一起使用,只需覆盖这一参数。只需将其替换为您要过滤的 admin.Model 类即可。

class TypeListFilter( admin.SimpleListFilter):
    """
    Provide filter for DnaComponentType (the actual "second level" type).

    This filter has one cosmetic problem, which is that it's setting is not
    automatically deleted if the category filter is changed. I tried but the
    request and queryset are all immutable. Instead, the queryset method is 
    checking for any missmatch between category and filter name and filtering
    is ignored if the category name doesn't match the current subType name.
    """
    title = 'Type'
    parameter_name = 'type'

    _class = None

    def lookups(self, request, model_admin):
        """
        Returns a list of tuples. The first element in each
        tuple is the coded value for the option that will
        appear in the URL query. The second element is the
        human-readable name for the option that will appear
        in the right sidebar.
        """
        if not u'category' in request.GET:
            return ()

        category_name = request.GET[u'category']
        types = self._class.objects.filter(subTypeOf__name=category_name)
        return ( (t.name, t.name) for t in types )

    def queryset(self, request, queryset):
        """
        Returns the filtered queryset based on the value
        provided in the query string and retrievable via
        `self.value()`.
        """
        if not u'category' in request.GET:
            return queryset

        category = request.GET[u'category']
        subtypes = self._class.objects.filter(subTypeOf__name=category)

        r = queryset.filter(componentType__subTypeOf__name=category)

        if not self.value():
            return r

        ## special case: missmatch between subtype and category
        ## which happens after switching the category
        if len(subtypes.filter(name=self.value())) == 0:
            return r

        return r.filter(componentType__name=self.value())
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将当前过滤器选择提供给 Django 中的另一个自定义 SimpleListFilter 的相关文章

  • 隐藏控制台并执行 python 脚本

    我正在尝试使用 pyinstaller 在 Windows 10 上使用 pyqt5 模块编译在 python 3 中构建的 python 脚本 该脚本在运行时隐藏窗口 为了编译我的脚本 我执行了以下命令 pyinstaller onefi
  • MySQL 的 read_sql() 非常慢

    我将 MySQL 与 pandas 和 sqlalchemy 一起使用 然而 它的速度非常慢 对于一个包含 1100 万行的表 一个简单的查询需要 11 分钟以上才能完成 哪些行动可以改善这种表现 提到的表没有主键 并且仅由一列索引 fro
  • 可视化时间序列时标记特定日期

    我有一个包含几年数据的时间序列 例如 ts pd Series np random randn 1000 index pd date range 1 1 2000 periods 1000 ts ts cumsum ts plot 我还有两
  • 将带有非字符串关键字的 dict 传递给 kwargs 中的函数

    我使用具有签名功能的库f args kwargs 我需要在 kwargs 参数中传递 python dict 但 dict 不包含关键字中的字符串 f 1 2 3 4 Traceback most recent call last File
  • 导入错误:无法导入名称 urandom

    我正在构建一个新的 Linux 环境 并在 Python 上看到以下错误 python c import random Traceback most recent call last File
  • 可重用的 Tensorflow 卷积网络

    我想重用来自Tensorflow 专业人士的 MNIST CNN 示例 http www tensorflow org tutorials mnist pros index md 我的图像尺寸为 388px X 191px 只有 2 个输出
  • 为 Keras 编写自定义数据生成器

    我将每个数据点存储在 npy 文件中 其中shape 1024 7 8 我想通过类似的方式将它们加载到 Keras 模型中ImageDataGenerator 所以我编写并尝试了不同的自定义生成器 但它们都不起作用 这是我改编的一个this
  • “分页文件太小,无法完成此操作”尝试训练 YOLOv5 对象检测模型时出错

    我有大约 50000 个图像和注释文件用于训练 YOLOv5 对象检测模型 我在另一台计算机上仅使用 CPU 训练模型没有问题 但需要太长时间 因此我需要 GPU 训练 我的问题是 当我尝试使用 GPU 进行训练时 我不断收到此错误 OSE
  • Emacs:调试Python的方法

    我把这个贴在程序员 stackexchange com https softwareengineering stackexchange com questions 29844 emacs methods for debugging pyth
  • 在 Django 中使用多处理时,应用程序尚未加载,出现异常

    我正在做一个 Django 项目并尝试提高后端的计算速度 该任务类似于 CPU 限制的转换过程 这是我的环境 Python 3 6 1 姜戈 1 10 PostgreSQL 9 6 当我尝试通过 python 多处理库并行计算 API 时
  • 将 Matlab MEX 文件中的函数直接嵌入到 Python 中

    我正在使用专有的 Matlab MEX 文件在 Matlab 中导入一些仿真结果 当然没有可用的源代码 Matlab 的接口实际上非常简单 因为只有一个函数 返回一个 Matlab 结构体 我想知道是否有任何方法可以直接从Python调用M
  • 如何点击 Google Trends 中的“加载更多”按钮并通过 Selenium 和 Python 打印所有标题

    这次我想单击一个按钮来加载更多实时搜索 这是网站的链接 该按钮位于页面末尾 代码如下 div class feed load more button Load more div 由于涉及到一些 AngularJS 我不知道该怎么做 有什么提
  • 对 Python 的 id() 感到困惑[重复]

    这个问题在这里已经有答案了 我可以理解以下定义 每个对象都有一个身份 类型和值 对象的身份 一旦创建就永远不会改变 你可能会认为它是 对象在内存中的地址 这is操作员比较身份 两个物体 这id 函数返回一个代表其值的整数 身份 我假设上面的
  • 使用 PIL 合并图像时模式不匹配

    我正在传递 jpg 文件的名称 def split image into bands filename img Image open filename data img getdata red d 0 0 0 for d in data L
  • 在Python中计算矩阵乘以其转置(AA^T)的最快方法

    在Python中将矩阵与其转置 AA T 相乘的最快方法是什么 我认为 NumPy SciPy 没有考虑使用例如时涉及的对称性 np dot or np matmul 得到的矩阵总是对称的 所以我可以想象有一个更快的解决方案 None
  • 使用 boto3 将 csv 文件保存到 s3

    我正在尝试写入 CSV 文件并将其保存到 s3 中的特定文件夹 存在 这是我的代码 from io import BytesIO import pandas as pd import boto3 s3 boto3 resource s3 d
  • 如何在特定时间启动Tornado周期性回调?

    目前在我的 Tornado 应用程序中 我正在使用定期调用回调PeriodicCallback每隔一小时 像这样 import tornado ioloop from tornado ioloop import PeriodicCallba
  • 使用 PuLP 进行线性优化,变量附加条件

    我必须用 Pull 解决 Python 中的整数线性优化问题 我解决了基本问题 现在我必须添加额外的约束 有人可以帮助我用逻辑指示器添加条件吗 逻辑限制是 如果 A gt 20 则 B gt 5 这是我的代码 from pulp impor
  • 张量流多元线性回归不收敛

    我正在尝试使用张量流训练具有正则化的多元线性回归模型 由于某种原因 我无法获取以下代码的训练部分来计算我想要用于梯度下降更新的误差 我在设置图表时做错了什么吗 def normalize data matrix averages np av
  • 用于获取有关 SVN 存储库信息的 Python 库?

    我正在寻找一个可以从 SVN 存储库中提取 至少 以下信息的库 not工作副本 修订号及其作者和提交消息 每个修订版中的更改 添加 删除 修改文件 有Python库可以做到这一点吗 对于作者和提交消息 我可以解析 db revprops 0

随机推荐