Method filter - Django admin extensions

Skip to content

# Method filter

##

## `MethodFilter`

Simple admin filter to call queryset's method if selected as `yes`.

### `as_filter(parameter_name, method=None, title=None)` `classmethod`

Factory for easier filter generation.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`parameter_name` | `str` | Parameter to bind this filter. | required
`method` | `str` | Method to call. Defaults to None. | `None`
`title` | `[type]` | Filters title. Defaults to None. | `None`

Source code in `pxd_admin_extensions/filters/method.py`

    @classmethod
    def as_filter(cls, parameter_name: str, method: str = None, title=None):
        """Factory for easier filter generation.

        Args:
            parameter_name (str): Parameter to bind this filter.
            method (str, optional): Method to call. Defaults to None.
            title ([type], optional): Filters title. Defaults to None.
        """
        return type(parameter_name + 'Filter' + cls.__name__, (cls,), {
            'parameter_name': parameter_name,
            'method_name': method or parameter_name,
            'title': title or parameter_name
        })

### `lookups(self, request, model_admin)`

Must be overridden to return a list of tuples (value, verbose value)

Source code in `pxd_admin_extensions/filters/method.py`

    def lookups(self, request, model_admin):
        return (
            (None, _('No')),
            ('1', _('Yes')),
        )

### `queryset(self, request, queryset)`

Return the filtered queryset.

Source code in `pxd_admin_extensions/filters/method.py`

    def queryset(self, request, queryset):
        if self.used_parameters.get(self.parameter_name) == '1':
            return getattr(queryset, self.method_name)()

        return queryset