Adama Camara Adama Camara - 1 year ago 101
Python Question

What to do when searching on more than one word with django filter

I made a filter where you can search on different keywords and it works.

My problem is that when i am trying to search on more than one keyword.

How do I make it possible to filter the search so it can separate each word?

Here is a picture how it looks:

First picture shows when i only search on one key word, and second shows when i search on two: enter image description here
enter image description here

Here is my code for The model class:

class Task(managers.Model):
keywords = models.ManyToManyField('Keyword', blank=True, related_name='event_set')
objects = managers.DefaultSelectOrPrefetchManager.from_queryset(managers.TaskQuerySet)()

And here is my Filter class:

class TaskFilterSet(BaseFilterSet):

keywords = django_filters.MethodFilter(action="filter_keywords")

class Meta:
model = models.Task

def filter_keywords(self, queryset, value):
from django.db.models import Q
return queryset.filter(Q(keywords__word__icontains=value))

Ev. Ev.
Answer Source

Lets suppose you are searching for the following Keywords: foo and boo. And you have the following relation:


You can iterate over object.keywords and see if one of the search objects you have matches one of the keywords in object. If it does, you return the filter containing that object.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download