Custom Filter using filterspecs

 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# Authors: Guglielmo Celata <guglielmo.celata at gmail.com>
#          
# File: <your project>/filters.py

from django.db import models
from django.utils.encoding import smart_unicode
from django.utils.translation import ugettext as _
from django.contrib.admin.filterspecs import FilterSpec

class IsLinkedFilterSpec(FilterSpec):
    """
    Adds filtering by existence of at least one related object.

    Note: this is a temporary hack.
    Django 1.4 implements a proper mechanism to define custom filters
    
    * Add this code in filters.py
    * Import the class in your models
    * set `my_model_field.is_linked_filter = True` for the given field in the class specification
    * add 'my_model_field' to the **list_filter** tuple in admin.py
    """
    
    def __init__(self, f, request, params, model, model_admin, field_path=None):
        super(IsLinkedFilterSpec, self).__init__(f, request, params, model,
                                                 model_admin, field_path)
        self.lookup_kwarg = '%s__isnull' % self.field_path
        self.lookup_val = request.GET.get(self.lookup_kwarg, None)
    
    
    def choices(self, cl):
        yield {'selected': self.lookup_val == None,
               'query_string': cl.get_query_string({},[self.lookup_kwarg]),
               'display': _('Any')}
        
        yield {'selected': self.lookup_val == 'False',
               'query_string': cl.get_query_string({self.lookup_kwarg: False}),
               'display': _('Yes')}
        
        yield {'selected': self.lookup_val == 'True',
               'query_string': cl.get_query_string({self.lookup_kwarg: True}),
               'display': _('No')}
        
    
    
    def title(self):
        return "Linked"
    


# registering the filter
FilterSpec.filter_specs.insert(0, (lambda f: getattr(f, 'is_linked_filter', False),
                                   IsLinkedFilterSpec))

More like this

  1. RelatedNullFilterSpec: django-admin custom filter all/null/not null/choices by Codeko 3 years, 6 months ago
  2. django-admin custom filter: IS NULL/IS NOT NULL by Eloff 4 years, 1 month ago
  3. Changing queryset of a ModelChoiceField by mimog 2 years, 9 months ago
  4. FilterSpec for ForeignKeys to auth.User with HTML input tag for ModelAdmin.list_filter by loic 2 years, 11 months ago
  5. Foreign Key list_filter wthout custom FilterSpec by haileris23 4 years, 2 months ago

Comments

(Forgotten your password?)