Usage

Using search_views.views.SearchListView

search_views.views.SearchListView is a class-based view derived from django.views.generic.list.ListView that you can inherit in your application's views to get the search functionalities.

Your views, as a descendant of django.views.generic.list.ListView, must be configured by providing template_name, a model or queryset property or a get_queryset_method. See the related django docs for more details.

You will also need to define:

  • the form_class attribute, that specifies the class derived from django.forms.Form that will be used to get a form instance, that will available via the form context variable in your template.
  • the filter_class attribute, that specifies the class derived from search_views.filters.BaseFilter used to map the form fields to the model properties and lookup methods.

Here's an example definition of a view:

from .models import Actor
from .forms import ActorSearchForm
from search_views.search import SearchListView

class ActorsSearchList(SearchListView):
    # regular django.views.generic.list.ListView configuration
    model = Actor
    paginate_by = 30
    template_name = "actors/actors_list.html"

    # additional configuration for SearchListView
    form_class = ActorSearchForm
    filter_class = ActorsFilter

The filter_class is resposible of mapping the fields defined in your form to
filter that will be performed on the base queryset. This is done by providing a subclass of search_views.filters.BaseFilter.

class search_views.filters.BaseFilter

This class is used to configure the main view class, by means of its search_fields attribute, that must be set to a python dictionary, where:

  • keys map to the fields of your form class.
  • values are either:
    • a list of field names of your model. In this case a simple text search is performed.
    • a configuration dictionary that specifies

      • fields: list of fields name to apply the filter to
      • operator: django queryset operator that is used to apply the filter.

      • fixed_filters: TBW

      • custom_query: TBW
      • value_mapper: TBW

Queries generated by different search_fields are ANDed, if a search field is defined for more than one field, are put together with OR.

Let's explore all the options. (TBW)

from .models import Actor
from .forms import ActorSearchForm
from search_views.search import SearchListView
from search_views.filters import BaseFilter

class ActorsFilter(BaseFilter):
    search_fields = {
        'search_text' : ['name', 'surname'],
        'search_age_exact' : { 'operator' : '__exact', 'fields' : ['age'] },
        'search_age_min' : { 'operator' : '__gte', 'fields' : ['age'] },
        'search_age_max' : { 'operator' : '__lte', 'fields' : ['age'] },  
    }

class ActorsSearchList(SearchListView):
    model = Actor
    paginate_by = 30
    template_name = "actors/actors_list.html"
    form_class = ActorSearchForm
    filter_class = ActorsFilter