python - 如何使用 django-filter 应用程序中的 MethodFilter?

标签 python django django-filters

我不知道如何在 django-filter 应用程序中使用 MethodFilter,我在文档中找不到它 (http://django-filter.readthedocs.org/en/latest/index.html)。我需要使用 from 和 to 输入日期字段创建过滤器。您知道我如何使用 MethodFilter 或其他方式执行此操作吗?

我有一些课:

class Product(django_filters.FilterSet):

    class Meta:
        model = Product
        fields = ['name', 'category', 'created_at]

我有字段 created_at,我想按 created_at(从和到)过滤产品。

最佳答案

要回答问题的如何使用 MethodFilter 部分,请在您的 FilterSet 上定义一个方法并将其指定为过滤器的 action

例如,要按用户名进行过滤,您可以执行以下操作:

class F(FilterSet):
    username = MethodFilter(action='filter_username')

    class Meta:
        model = User
        fields = ['username']

    def filter_username(self, queryset, value):
        return queryset.filter(
            username=value
        )

关于python - 如何使用 django-filter 应用程序中的 MethodFilter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26656153/

相关文章:

python - 在 Pandas 中找到另一列中的重复数字时如何生成一列连续数字 : Python

php - 请建议一些替代 Drupal 的方法

python - 导入 django_filters.rest_framework 错误

django - 通过过滤对象列表来过滤对象列表

python - 根据条件更改 tensorflow 张量的值

python - NumPy Sum(带轴)如何工作?

django - 使用 Django 查询集在列中搜索多个单词

python - 谷歌应用引擎 : upload throws "TemplateDoesNotExist: index.html" error

python - Django 模板列表的第一个元素

python - 我可以在与 pyodbc 和 MS SQL Server 的一个连接上使用多个游标吗?