Use OR clause instead AND in django-filter

I'm working with the django-filter + django rest framework. I want to search a term with the OR clause. I have this filter:

class ItemFilter(filters.FilterSet):
    name = filters.CharFilter(field_name="name")
    barcode = filters.CharFilter(field_name="barcode")

    class Meta:
        model = Item
        fields = ['name', 'barcode']

when I send a query param like https://url?barcode=q&name=q django-filter searchs:

SELECT * FROM item where name = 'q' AND barcode = 'q'

How can I configure to search?:

SELECT * FROM item where name = 'q' OR barcode = 'q'

One of the options would be using SearchFilter in your view to filter on multiple fields:

from rest_framework import filters

class YourView(generics.ListAPIView):
    queryset = Item.objects.all()
    serializer_class = ...
    filter_backends = [filters.SearchFilter]
    search_fields = ['name', 'barcode']

And then use search keyword in url query params: https://url?search=q

Back to Top