If you want to search by two model fields in one form field, you can use a Q object with the operator | which means or
views.py:
from django.views.generic import ListView from django.db.models import Q class PlaceListView(ListView): model = Place def get_queryset(self): # Получаем не отфильтрованный кверисет всех моделей queryset = super(FlavorListView, self).get_queryset() q = self.request.GET.get("q") if q: # Если 'q' в GET запросе, фильтруем кверисет по данным из 'q' return queryset.filter(Q(name__icontains=q)| Q(keywords__icontains=q)) return queryset
urls.py:
urlpatterns = patterns( '', url(r'^place_search/$', PlaceListView.as_view, name='place_search'),)
Form in the template:
<form action="{% url "place_search" %}" method="GET"> <input type="text" name="q" /> <button type="submit">search</button> </form> <!--> Сюда можно включить шаблон с результатами через include Или выделить для него отдельный блок <--> {% include "template/result_template.html" %}
Template with search form results:
<h1>Places</h1> <ul> {% for place in object_list %} <li>{{ place.name }}</li> {% endfor %} </ul>
UPD
If you want to search for the occurrence of each word, separated by commas, you can break a line into a list and look for an entry in it.
.... q = self.request.GET.get("q") q_lst = q.split(",") return queryset.filter(Q(name__in=q_lst)| Q(keywords__in=q_lst))