Login

Custom Filter using filterspecs

Author:
guglielmocelata
Posted:
March 3, 2012
Language:
Python
Version:
1.3
Score:
0 (after 0 ratings)

This snippet is based on #1051.

It adds filtering by existence of at least one related object. It is an example of how to simply subclass the FilterSpec class, in order to build a custom Filter.

The comment in the code contains instructions on how to implement it in a real project.

 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. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

Please login first before commenting.