Tastypie filtering with multiple values

一笑奈何 提交于 2019-11-30 03:31:56

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}

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 })

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()

/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.

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' ] }

```

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!