How to Filter by Status in Django Rest Framework with Square Brackets in Query Params

I'm encountering an issue with filtering a model by status in Django Rest Framework. Here's my current setup:

When I filter using status=1,14, it works perfectly:


class DepartmentFilter(filters.FilterSet):
    search = filters.CharFilter(method='filter_search')
    status = filters.CharFilter(method='filter_status')

    class Meta:
        model = Department
        fields = ['search', 'status']

    def filter_search(self, queryset, name, value):
        print("filter_search", value)
        return queryset.filter(Q(token__icontains=value))
    
    def filter_status(self, queryset, name, value):
        print("filter_status", value)  # Verificar que el filtre s'executa
        if value:
            status_values = value.split(',')
            return queryset.filter(status__id__in=status_values)
        return queryset
    

However, I'm having trouble capturing the query parameter when I use status[]=1,14.

I've tried the following without success:

status = filters.CharFilter(method='filter_status[]')

status = filters.CharFilter(method='filter_status%5B%5D')

There doesn't seem to be a way to create a function to capture this.

Resolving status[] is a first step because ultimately, I want to work with the call filters[status][] = 1,14. I haven't found a way to handle this.

Can anyone provide some guidance?

Thank you!

It is not the method, it is the name of the "source" that should change, so:

class DepartmentFilter(filters.FilterSet):
    search = filters.CharFilter(method='filter_search')
    status = filters.CharFilter(method='filter_status', field_name='status[]')

    class Meta:
        model = Department
        fields = ['search', 'status']

    def filter_search(self, queryset, name, value):
        return queryset.filter(Q(token__icontains=value))

    def filter_status(self, queryset, name, value):
        if value:
            status_values = value.split(',')
            return queryset.filter(status__id__in=status_values)
        return queryset

That being said, adding [] to a field name is a relic from PHP, in (most) Django applications, this is not used.

Back to Top