Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django – How to add "or" condition to queryset.filter in custom filter

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading