Advance filtering with list of elements using django tastypie
<p>I am using <a href="https://pypi.python.org/pypi/django-multiselectfield" rel="nofollow">MultiSelectField</a> to select multiple choices within my django admin it creates an array for fields in the backend of all the choices I select. I then use <code>django tastypie's</code> List Field to make sure its a list of elements the api returns.</p>

<p>My problem is as I am building the filter when I put <code>/api/?brand_category=Clothing&amp;q=athletic,bohemian</code> in the browser it does not return anything but an empty list. So I want to know if I am doing something wrong? Or not building my filters correctly?</p>

<p><strong>models.py</strong></p>

<pre><code>class Brand(models.Model):

    # category
    brand_category = MultiSelectField(max_length=100, blank=True, choices=categories))

    # style
    brand_style = MultiSelectField(max_length=100, choices=styles, blank=True)
</code></pre>

<p><strong>api.py</strong></p>

<pre><code>class LabelResource(ModelResource):

    brand_category = fields.ListField(attribute='brand_category')

    brand_style = fields.ListField(attribute='brand_style')

    class Meta:

        filtering = {
            "brand_category": ALL,
            "brand_style": ALL,
            "q": ['exact', 'startswith', 'endswith', 'contains', 'in'],

        }


def build_filters(self, filters=None):
    if filters is None:
        filters = {}

    orm_filters = super(LabelResource, self).build_filters(filters)


    if('q' in filters):
        query = filters['q']

        qset = (
            Q(brand_style__in=query) 
        )

        orm_filters.update({'custom': qset})

    return orm_filters

def apply_filters(self, request, applicable_filters):
    if 'custom' in applicable_filters:
        custom = applicable_filters.pop('custom')

    else:
        custom = None

    semi_filtered = super(LabelResource, self).apply_filters(request, applicable_filters)

    return semi_filtered.filter(custom) if custom else semi_filtered
</code></pre>

<p><strong>JSON Response</strong></p>

<pre><code>{
  "brand_category": [
    "Clothing"
  ],
  "brand_style": [
    "athletic",
    "bohemian",
    "casual"
  ]
}
</code></pre>

<p><code>filters['q']</code> is a <code>athletic,bohemian</code> string. <code>__in</code> lookup need a list or tuple.</p>

<pre><code>query = filters['q'].split(',')
</code></pre>

python django tastypie