【问题标题】:How to enable partial searches for all fields?如何启用对所有字段的部分搜索?
【发布时间】:2021-07-14 22:39:57
【问题描述】:

想象一下,我有以下 filters.py:

class ActionFilter(django_filters.FilterSet):
    class Meta:
        model = Action
        fields = "__all__"

现在,我想在我的模型中启用对 Charfield 字段的部分搜索。如何启用?

编辑

class ActionFilter(django_filters.FilterSet):
    name = django_filters.CharFilter(field_name = 'name', lookup_expr='icontains')
    description = django_filters.CharFilter(field_name = 'description', lookup_expr='icontains')
    class Meta:
        model = Action
        fields = "__all__"

HTML:

        <div class="card-body">
            {% load django_tables2 %}
            {% render_table table %}
            {% if table.filter %}
                <form action="" method="get" class="form form-inline">
                    {% bootstrap_form table.filter.form layout='inline' %}
                    {% bootstrap_button 'filter' %}
                </form>
            {% endif %}
        </div>
    </div>
</div>

tables.py 将 django_tables2 导入为表

from .models import Action, ControlTest
from .filters import ActionFilter

class actionTable(tables.Table):
    action_report = tables.Column(accessor='report.type')
    title_report = tables.Column(accessor='report.name')
    date_report = tables.Column(accessor='report.date')
    business_unit = tables.Column(accessor='bu.name')
    wallet_holder = tables.Column(accessor='control.bu')
    owner = tables.Column(accessor='owner')
    title_finding = tables.Column(accessor='actionr')
    description_finding = tables.Column(accessor='actionr.description')
    

    class Meta:
        Action.filter = ActionFilter
        model = Action
        fields = ('id', 'action_report', 'title_report', 'date_report', 'due_date','priority','business_unit', 'wallet_holder', 'owner', 'delegate', 'reviewer1', 'reviewer2', 'title_finding', 'description_finding','Action_Comments',
        'name', 'description', 'ControlID', 'ReportID', 'BUid', 'UserID_as_ActionOwner', 'UserID_as_ActionOwner', 'UserID_as_Actionreviewer', 'Priority',
        'status', 'Action_History', 'Review_Comments', 'documentation', 'referencenumber')

【问题讨论】:

    标签: python django filter


    【解决方案1】:

    你的问题对我来说不是很清楚(即你所说的部分是什么意思)。

    但我认为您的意思是该字段是否包含您过滤的某些文本,即标题为“这是最好的例子”的 qs 中的“The”。如果这就是您要查找的内容,则需要使用i__contains

    title = django_filters.CharFilter(lookup_expr='icontains',field_name='title')

    【讨论】:

    • 感谢您的评论!如果我要指定的字段是 Meta 中的 all 类型怎么办?我可以为它们指定一个图标吗?
    • 你能解释一下你的意思是什么
    • 是的,当然。我在 html 中有以下代码(请参阅编辑),当我添加 name = django_filters.CharFilter 时,它让我在前端包含名称。所以你会认为它会起作用:它现在确实忽略了区分大小写,但没有部分搜索。我做错了什么?
    • 嗯,我认为您不能将字段提供为“all”也许可以尝试在数组中添加字段,如fields=['name','description'],告诉我它是否有效。跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-28
    相关资源
    最近更新 更多