Tastypie filtering with multiple values

后端 未结 5 755
你的背包
你的背包 2020-12-28 19:02

I had a simple question on filtering in tastypie.

I want to filter with multiple values. For example:

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

相关标签:
5条回答
  • 2020-12-28 19:04

    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}

    0 讨论(0)
  • 2020-12-28 19:05

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

    0 讨论(0)
  • 2020-12-28 19:06

    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()
    
    0 讨论(0)
  • 2020-12-28 19:20

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

    ```

    0 讨论(0)
  • 2020-12-28 19:24

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

    0 讨论(0)
提交回复
热议问题