I have a basic Django model like:
class Business(models.Model):
name = models.CharField(max_length=200, unique=True)
email = models.EmailField()
Taking the idea in astevanovic's answer and cleaning it up a bit, the following should work and is more succinct.
The main difference is that apply_filters is made more robust by using None
as the key instead of custom
(which could conflict with a column name).
def build_filters(self, filters=None):
if filters is None:
filters = {}
orm_filters = super(BusinessResource, self).build_filters(filters)
if 'query' in filters:
query = filters['query']
qset = (
Q(name__icontains=query) |
Q(description__icontains=query) |
Q(email__icontains=query)
)
orm_filters.update({None: qset}) # None is used as the key to specify that these are non-keyword filters
return orm_filters
def apply_filters(self, request, applicable_filters):
return self.get_object_list(request).filter(*applicable_filters.pop(None, []), **applicable_filters)
# Taking the non-keyword filters out of applicable_filters (if any) and applying them as positional arguments to filter()