user12137867
user12137867

Reputation:

Multi searching DJANGO

I have just finished one tutorial where a user can search cities, but it is possible to enter only one city. If i would like to search Oslo, Budapest in the same time it is impossible. Do you know what can I add to change it?

Views:

from django.views.generic import TemplateView, ListView
from django.db.models import Q
from .models import City

class HomePageView(TemplateView):
    template_name='home.html'

class SearchResultsView(ListView):
    model = City
    template_name = 'search_results.html'

    def get_queryset(self):
        query = self.request.GET.get('q')
        object_list = City.objects.filter(
            Q(name__icontains=query) | Q(state__icontains=query)
        )
        return object_list

TEMPLATE:

<h1>Search Results</h1>

<ul>
  {% for city in object_list %}
    <li>
      {{ city.name }}, {{ city.state }}
    </li>
  {% endfor %}
</ul>

Upvotes: 0

Views: 137

Answers (2)

Dipen Dadhaniya
Dipen Dadhaniya

Reputation: 4630

We can do something like this:

from django.db.models import Q    

def get_queryset(self):
    queries = self.request.GET.get('q')
    queries = queries.split(', ')        

    q = Q()
    for query in queries:
        q |= (Q(name__icontains=query) | Q(state__icontains=query))

    return City.objects.filter(q)

You might want to read: Complex lookups with Q objects

Upvotes: 1

RHSmith159
RHSmith159

Reputation: 1592

You can filter against multiple names like this:

City.objects.filter(name__in=list_of_names)

where list_of_names is an object of type list e.g. list_of_names = ['name_1', 'name_2']

I'm not sure how you are generating your query, but you would need to change that to allow the user to input multiple cities too.

Upvotes: 0

Related Questions