Search code examples
djangodjango-admindjango-admin-filters

Implement field wise searching in Django Admin


I'm using Django 2.0

I have to add functionality to search for fields from model with different input fields for different columns.

I'm following this tutorial from medium.com and have implemented it like

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'
    ]

But this is giving error as

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.

Solution

  • In the list_filter you have to give your custom filter class name.

    list_filter = [YourFilterClass]
    

    Don't give it as a string.