3

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!

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

1 Comment

No, using field_name='status[]' or field_name='status%5B%5D' still doesn't trigger the filter_status function in the filter. In any case, I have modified the frontend logic to work with status=1,14 Thanks anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.