[Fixed]-Tastypie filtering with multiple values

19👍

Hmm,

You can do this:

/api/v1/message/?accountId__in=1&accountId__in=5&accountId__in=12

PS: in filtering meta attribute, add {'accountId': ALL}

10👍

The most recent version seems to work pretty easily – just use an “__in”:

/api/v1/message/?accountId__in=1,5,12

(I assume you will need an entry in your resources Meta class, filtering = { ‘accountId’ : ALL })

9👍

You’ll have to build and apply a filter. Here’s a small snippet, it’s better to build the filter in build_filters, then apply it in apply_filters, but you’ll get the idea

class Foo(ModelResource):

    # regular stuff goes here...

    def apply_filters(self, request, applicable_filters):
        base_object_list = super(Foo, self).apply_filters(request, applicable_filters)
        query = request.GET.get('query', None)
        ids = request.GET.get('ids', None)
        filters = {}
        if ids:
            ids = ids.replace('+', ' ').split(' ')
            filters.update(dict(id__in=ids))
        if query:
            qset = (
                Q(title__icontains=query, **filters) |
                Q(description__icontains=query, **filters)
            )
            base_object_list = base_object_list.filter(qset).distinct()
        return base_object_list.filter(**filters).distinct()

3👍

/api/v1/message/?accountId__in=1,5,12
this is the right way to me, it is easy and straightforward.

/api/v1/message/?accountId__in=1&accountId__in=5&accountId__in=12
this way is strange and looks ugly.

of course, you need to add filtering = { 'accountId' : ALL } in the resource META.

1👍

You must declare the filtering columns in class Meta. This is a security by obscurity rule.

So, the accountId__in=[..] rule is one of these.

“`
filtering = { ‘accountId’ : ALL }
OR
filtering = { ‘accountId’ : [ …, ‘in’ ] }

“`

Leave a comment