Tastypie is a pretty good REST interface under Django. One thing everyone wants from it is filtering. Tastypie provides a simple one through class Meta for ModelResource

class Meta:
    filtering = {
        'fieldname': ALL

As of now, we could passing GET parameters just like you do on model filter.


However, it sucks having tons of filters while you can do just one query word like


Basicly, filters in ModelResource works by going through build_filters then apply_filters. With the idea above, we need to override something in ModelResource. It's build_filters(self, filters=None).

def build_filters(self, filters=None):
    if filters is None:
        filters = {}
    orm_filters = super(YyyyResource, self).build_filters(filters)

    if 'q' in filters:
        query = filters['q']
        orm_filters['fieldname1__contains'] = filters['q']
        orm_filters['fieldname2__contains'] = filters['q']
    return orm_filters

By the way, it's AND filtering; if we want OR filtering, we will need to get much more complicated that just simple filter. Q is the answer, but in order to use it, we need to override apply_filters(self, request, applicable_filters) as well. The easiest thing is like following:-

def apply_filters(self, request, applicable_filters):
    base_object_list = super(YyyyResource, self).apply_filters(request, applicable_filters)
    if 'q' in filters:
        return base_object_list.filter(
                   Q(fieldname1__contains=filters['q']) |
    return base_object_list

There you go. It's exactly what we do in regular Django. Not to mention apply_filters which has request that contains user too.