Login

Generic model filter from request GET data

Author:
genbit
Posted:
July 31, 2011
Language:
Python
Version:
1.3
Tags:
filter forms queryset
Score:
2 (after 2 ratings)

You just use standart django query terms, for example:

<form>
    <input class="field_text filter_from" type="text" name="cost__gte" placeholder="from" value="{% if request.GET.cost__gte %}{{ request.GET.cost__gte }}{% endif %}">            
   <input class="field_text filter_to" type="text" name="cost__lte" placeholder="to" value="{% if request.GET.cost__lte %}{{ request.GET.cost__lte }}{% endif %}">
</form>

model:

class Object(models.Model):
    cost = models.IntergerField()
    objects = ObjectManager()
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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

More like this

  1. load m2m fields objects by dirol 6 years, 2 months ago
  2. Multiple-Submit-Button Widget for Choice Field by Archatas 8 years ago
  3. FieldAccessForm (per-field user access for forms derived from models) by Killarny 7 years, 10 months ago
  4. Verbose template filter : avoid too many if by romain-hardouin 8 years, 2 months ago
  5. Hidden Forms by insin 9 years, 1 month ago

Comments

diverman (on August 1, 2011):
<p>Hi, this is nice. I made something similar. Problem with this is, when invalid filters are passed to filter(). It will not not raise an exception from filter(), but at the time of queryset evaluation.</p> <p>PS: try to modify your snippet to support other logical operators than AND...</p>

#

Please login first before commenting.