from django.core.exceptions import ValidationError from django.db import models from django.db.models.sql import constants from django.utils.translation import ugettext_lazy as _ class ObjectManager(models.Manager): def filter_from_request(self, request): """ Generic model filter from request GET data """ qs = self.get_query_set() filters = dict() fields = [f.name for f in self.model._meta.fields] for p in request.GET: if constants.LOOKUP_SEP in p: field_name, field_qterm = p.split(constants.LOOKUP_SEP) else: field_name = p if field_qterm and field_qterm not in constants.QUERY_TERMS: continue if field_name in fields: if request.GET.get(p) != '': filters[p] = request.GET.get(p) try: qs = qs.filter(**filters) except ValueError, e: raise ValidationError(_(u'Error filter data')) return qs