Advertisement
black_eagle

#filters.py

Aug 4th, 2011
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.84 KB | None | 0 0
  1. #filters.py
  2.  
  3. from django.db import models
  4. from django.utils.encoding import smart_unicode, iri_to_uri
  5. from django.contrib.admin.util import get_model_from_relation, \
  6.     reverse_field_path, get_limit_choices_to_from_path
  7.  
  8. from django.contrib.admin.filterspecs import RelatedFilterSpec
  9.  
  10. from models import Category
  11.  
  12.  
  13. class CategoryFilterSpec(RelatedFilterSpec):
  14.     def __init__(self, f, request, params, model, model_admin,
  15.                  field_path=None):
  16.         super(CategoryFilterSpec, self).__init__(
  17.             f, request, params, model, model_admin, field_path=field_path)
  18.  
  19.         other_model = get_model_from_relation(f)
  20.         if isinstance(f, (models.ManyToManyField,
  21.                           models.related.RelatedObject)):
  22.             # no direct field on this model, get name from other model
  23.             self.lookup_title = other_model._meta.verbose_name
  24.         else:
  25.             self.lookup_title = f.verbose_name # use field name
  26.         rel_name = other_model._meta.pk.name
  27.         self.lookup_kwarg = '%s__%s__in' % (self.field_path, rel_name)
  28.         self.lookup_kwarg_isnull = '%s__isnull' % (self.field_path)
  29.         self.lookup_val = request.GET.get(self.lookup_kwarg, None)
  30.         self.lookup_val_isnull = request.GET.get(
  31.                                       self.lookup_kwarg_isnull, None)
  32.         lookup_choices = f.get_choices(include_blank=False)
  33.         self.lookup_choices = []
  34.         for pk_val, val in lookup_choices:
  35.             c = Category.objects.get(pk = pk_val)
  36.            
  37.             if c.parent == None:
  38.                 q = str(pk_val)+','
  39.                 for p in Category.objects.filter(parent=pk_val):
  40.                     q = q+str(p.pk)+','
  41.                 q = q[:-1]
  42.                 self.lookup_choices.append((q, val))
  43.             else:
  44.                 self.lookup_choices.append((pk_val, val))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement