Newtt
Newtt

Reputation: 6190

Filter in multiple parameters in query string

I've got a django app that has a filter as one of it's features.

The filter values are decided from a checkbox which is sent to the django backend using ajax as follows:

$('input.type-check').on('click', function(){
      var a = $(this).prop('checked');
      if(a == true){
          elem.push($(this).attr('data-role'));
      }else{
          elem.splice($(this).attr('data-role'));
      }
      var cats = '';
      $.each(elem, function(i){
          cats += elem[i];
      });
      var xurl ='/filter?category='+cats;
      $.ajax({
          type: 'GET',
          url: xurl,
          success: function(data){
              $('div.products').html(data);
          }
      })
  });

The /filter$' url is mapped to thefitlered` view which is:

def filtered(request):
  if 'category' in request.GET and request.GET['category']:
      cat = request.GET['category']
      ct = Product.objects.filter(category__in=cat)
      diction = {'prods': ct}
      return render(request, 'filter.html', diction)

It works when only one category is sent as parameter. However, when I send multiple, it gives no results.

Eg:

filter?category=Dairy will return the product that's associated with that category. However, filter?category=Dairy,Plastics or filter?category=DairyPlastics (which is from the above mentioned Javascript snippet) returns no result.

I've tried putting the category inside brackets in the view as follows [cat] but that doesn't help either. What should I do to make it return results?

Upvotes: 0

Views: 2013

Answers (1)

karthikr
karthikr

Reputation: 99640

The issue is, you are neither specifying a delimiter to demarcate the categories, not are you separating the categories in the view.

Try this:

In JQuery,

var cats = elem.join(', ')
var xurl ='/filter?category='+cats;

And in the view:

def filtered(request):
    if request.GET.get('category'):
        cat = request.GET.get'category')
        cat_list = [c.strip() for c in cat.split(',')]
        ct = Product.objects.filter(category__in=cat_list).distinct()
        #You might need a distinct clause too, to remove duplicates

        diction = {'prods': ct}
        return render(request, 'filter.html', diction)

This would work for a single category v/s a list of categories

Upvotes: 2

Related Questions