Skip to content

Instantly share code, notes, and snippets.

@edgartaor
Last active March 31, 2020 08:52
Show Gist options
  • Save edgartaor/53de162f06ac49e770f8 to your computer and use it in GitHub Desktop.
Save edgartaor/53de162f06ac49e770f8 to your computer and use it in GitHub Desktop.
Filter a field that contains any word in a phrase [Django-filters]
class ItemFilter(django_filters.FilterSet):
min_price = django_filters.NumberFilter(name='price', lookup_type='gte')
max_price = django_filters.NumberFilter(name='price', lookup_type='lte')
category = django_filters.CharFilter(name='category__slug', lookup_type='iexact')
title = django_filters.MethodFilter(name='title', action='icontains_any_word_title')
description = django_filters.MethodFilter(name='description', action='icontains_any_word_description')
class Meta:
model = Item
fields = ['category', 'min_price', 'max_price', 'negotiable', 'title', 'description']
def icontains_any_word_title(self, queryset, value):
query_words = str(value).split(" ") #Get the word in a list
for w in query_words:
if len(w) < 3: #Min length
query_words.remove(w)
if not query_words:
return queryset
return queryset.filter(reduce(lambda x, y: x | y, [Q(title__icontains=word) for word in query_words]))
def icontains_any_word_description(self, queryset, value):
query_words = str(value).split(" ")
for w in query_words:
if len(w) < 3:
query_words.remove(w)
if not query_words:
return queryset
return queryset.filter(reduce(lambda x, y: x | y, [Q(description__icontains=word) for word in query_words]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment