goinnn/django-multiselectfield

Filtering Problem

PedroPini opened this issue · 3 comments

Hi my problem is I can select multiple categories for my item and on my website I have a filter checkbox where the user can check and filter the items based on the categories

On my model I created a category = MultiSelectField(choices=CATEGORY_CHOICES), it works like a charm on django admin. But when it comes to filter on my view I am facing problems in getting the right data returned

I am sending an array ['IT', 'PK', 'CB']

and trying to do like this on my view.py

using
Item.objects.filter(category__icontains=category)

is the closest that I could get from getting my data right

I've already tried using __in, __contains
the problem is I if the user check 3 categories if one product doesnt have one if these 3 it dont retrieve

@PedroPini how to solve this problem? i'm solving this way :
Item.objects.filter(Q(category__icontains='IT') | Q(category__icontains='PK') | Q(category__icontains='CB'))

Cheers

hi @CARocha in the end, I fixed using array models with postgres database.

You can use a regex filter, e.g. category__regex=r'(^|,)%s(,|$)' % ['IT', 'PK', 'CB'])