Pergunta

Given the search term "big file larger desk", how would I search for 1) any of the results; and 2) all of the results.

The search I am currently doing is:

results = Path.objects.filter(path__icontains=search)

What I need to do is something along the lines of:

results = Path.objects.filter(path__icontains=search.split())

How would I do both of these? (OR or AND)

Foi útil?

Solução 2

The first thing you need to know is that you are not actually hitting the database when you filter, so you can do the filtering multiple times without losing to much performance, a first approach can be:

results = Path.objects.all()
for s in search.split():
    results = results.filter(path__icontains = s)

that is for AND ans you can use a similar approach for or.

Outras dicas

from django.db.models import Q
from operator import or_

# AND - use argument unpacking
Path.objects.filter(*(Q(path__icontains=s)
                      for s in search.split()))

# OR - use reduce
Path.objects.filter(reduce(or_, (Q(path__icontains=s)
                                 for s in search.split())))

Build a list comprehension and use the reduce function:

keywords = search.strip().split()
list_path_qs = [Q(path__icontains=x) for x in keywords]
final_q = reduce(operator.and_, list_path_qs)
results = Path.objects.filter(final_q)[:100]
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top