django-filter for multiple values parameter
To filter multiple values in Django using django-filter, you can follow these steps:
Install django-filter: You need to install the django-filter package in your Django project. You can do this by running the following command in your terminal:
pip install django-filter
Import the required modules: In your Django view or filter file, import the necessary modules from django_filters:
from django_filters import rest_framework as filters
Create a filter class: Define a filter class that inherits from the
filters.FilterSet
class. This class will define the fields and filters that you want to apply to your queryset. For example:python class MyFilter(filters.FilterSet): name = filters.CharFilter(lookup_expr='icontains') age = filters.NumberFilter(lookup_expr='exact') status = filters.ChoiceFilter(choices=STATUS_CHOICES)
Apply the filter class to your view: In your view, instantiate the filter class and apply it to your queryset. For example:
python class MyView(ListAPIView): queryset = MyModel.objects.all() serializer_class = MySerializer filter_backends = [DjangoFilterBackend] filterset_class = MyFilter
Use the filter parameters: Now, you can use the filter parameters in your API endpoints. You can pass multiple values for a field by separating them with commas. For example:
/api/myview/?name=value1,value2&age=20,30&status=active,inactive
This will filter the queryset based on the provided values for each field.
That's it! By following these steps, you can use django-filter to filter your queryset based on multiple values in Django.