在Django Admin中实现字段搜索

时间:2018-05-02 12:54:57

标签: django django-admin django-admin-filters

我正在使用Django 2.0

我必须添加功能来搜索模型中的字段,其中包含不同列的不同输入字段。

我正在关注来自medium.com的this tutorial,并将其实现为

models.py

class WallmartRecord(models.Model):
    name = models.CharField(max_length=250)
    upc = models.CharField(max_length=100)
    price = models.CharField(max_length=100)
    category = models.CharField(max_length=250)

    class Meta:
        db_table = 'wallmart_records'

    def __str__(self):
        return self.name

admin.py

class InputFilter(admin.SimpleListFilter):
    template = 'admin/input_filter.html'

    def queryset(self, request, queryset):
        pass

    def lookups(self, request, model_admin):
        return ((),)

    def choices(self, changelist):
        # Grab only the "all" option.
        all_choice = next(super().choices(changelist))
        all_choice['query_parts'] = (
            (k, v)
            for k, v in changelist.get_filters_params().items()
            if k != self.parameter_name
        )
        yield all_choice


class WallmartNameFilter(InputFilter):
    parameter_name = 'name'
    title = _('Name')

    def queryset(self, request, queryset):
        if self.value() is not None:
            name = self.value()

            return queryset.filter(
                name=name
            )


@admin.register(WallmartRecord)
class WallmartRecordAdmin(admin.ModelAdmin):
    list_filter = [
        'WallmartNameFilter',
        'not_exists_in_amazon',
        'arbitrase_generated'
    ]

但这是错误的

SystemCheckError: System check identified some issues:

ERRORS:
<class 'arbitrase.admin.WallmartRecordAdmin'>: (admin.E116) The value of 'list_filter[0]' refers to 'WallmartNameFilter', which does not refer to a Field.

1 个答案:

答案 0 :(得分:1)

在list_filter中,您必须提供自定义过滤器类名。

list_filter = [YourFilterClass]

不要把它作为一个字符串。