Home > Mobile >  Django - How to add "or" condition to queryset.filter in custom filter
Django - How to add "or" condition to queryset.filter in custom filter

Time:04-09

i want to make a search filter which searches in multiple fields with multiple conditions, using only one search field. I have this filters.py file:

import django_filters
from .models import Product


class ProductFilter(django_filters.FilterSet):
    q = django_filters.CharFilter(method='search_filter', label='Cerca')

    class Meta:
        model = Product
        fields = ['q']

    def search_filter(self, queryset, name, value):
        return queryset.filter(name__icontains=value, sku__iexact=value)

but return queryset.filter(name__icontains=value, sku__iexact=value) doesn't work, neither return queryset.filter(Product(name__icontains=value) | Product(sku__iexact=value)) How can i do this?

CodePudding user response:

You can filter with Q objects [Django-doc]:

import django_filters
from django.db.models import Q
from .models import Product

class ProductFilter(django_filters.FilterSet):
    q = django_filters.CharFilter(method='search_filter', label='Cerca')

    class Meta:
        model = Product
        fields = ['q']

    def search_filter(self, queryset, name, value):
        return queryset.filter(Q(name__icontains=value) | Q(sku__iexact=value))
  • Related