Exists Filter OneToOneField in Admin

 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
# File: filterspecs.py
from django.db import models
from django.contrib.admin.util import get_model_from_relation
from django.contrib.admin.filterspecs import FilterSpec
from django.utils.translation import ugettext as _

class OneToOneExistsFilterSpec(FilterSpec):
    def __init__(self, f, request, params, model, model_admin,
                 field_path=None):
        super(OneToOneExistsFilterSpec, self).__init__(f, request, params,
                                                       model, model_admin,
                                                       field_path=field_path)
        other_model = get_model_from_relation(f)
        if isinstance(f, (models.ManyToManyField,
                          models.related.RelatedObject)):
            # no direct field on this model, get name from other model
            self.lookup_title = other_model._meta.verbose_name
        else:
            self.lookup_title = f.verbose_name # use field name
        self.lookup_kwarg = '%s__isnull' % self.field_path
        self.lookup_val = request.GET.get(self.lookup_kwarg, None)
    
    def title(self):
        return self.lookup_title

    def choices(self, cl):
        for k, v in ((_('All'), None), (_('Yes'), 'False'), (_('No'), 'True')):
            yield {'selected': self.lookup_val == v,
                   'query_string': cl.get_query_string(
                                   {self.lookup_kwarg: v},
                                   [self.lookup_kwarg]),
                   'display': k}

# registering the filter
FilterSpec.filter_specs.insert(0, (lambda f: getattr(f.field, 'exists_filter', False),
                                   OneToOneExistsFilterSpec))

More like this

  1. Finding related objects for instances in a queryset by akaihola 3 years, 1 month ago
  2. Alphabetic filter for admin by semente 5 years, 7 months ago
  3. Bind Administration by ashcrow 5 years, 7 months ago
  4. render_markup filter, specify the markup filter as a string by exogen 7 years ago
  5. JSONField by deadwisdom 6 years, 8 months ago

Comments

declanshanaghy (on February 7, 2012):

The register portion does not work correctly for all field types, try this:

django.contrib.admin.filterspecs.FilterSpec.filter_specs.insert( 0, (lambda f: (hasattr(f, 'field') and getattr(f.field, 'exists_filter', False)), OneToOneExistsFilterSpec))

#

(Forgotten your password?)