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
This doesnt work. Any idea how i can do this?
Do i need to use advanced filtering? If yes, how do I go about creating such a filter? A simple effortless example of puesdo-code would be great!
Thanks!
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' ] }
```
来源:https://stackoverflow.com/questions/11436229/tastypie-filtering-with-multiple-values