【问题标题】:Implement field wise searching in Django Admin在 Django Admin 中实现字段智能搜索
【发布时间】:2018-10-12 14:17:57
【问题描述】:

我正在使用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.

【问题讨论】:

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


    【解决方案1】:

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

    list_filter = [YourFilterClass]
    

    不要把它作为字符串给出。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-10
      • 2013-05-23
      • 1970-01-01
      • 2021-06-26
      • 2012-01-13
      • 2019-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多