views:

530

answers:

2

I'm working on a custom Django Admin FilterSpec (covered already on SO #991926). My FilterSpec is a replacement for the default filter on ForeignKey(User), and basically replaces the list of all users with three only choices, all, mine, and others.

For example, if I applied the custom filterspec to the field created_by it would add an admin filter with All, Created by Me, and Created by Others. Everything works except the negative filter, Created by Others.

I've been attempting to achieve this by appending __not to the query as so:

def choices(self, cl):
    yield {
            'selected': self.lookup_val == self.user.pk,
            'query_string': cl.get_query_string({'%s__not' % self.field.name: self.user.pk}),
            'display': capfirst('%s Others' % self.field.verbose_name)
        }

It doesn't seem that Django supports filtering in the negative like this. I've also experimented with having it do a __gte and __lte but the filterspec only uses the first one it finds (gte), dropping the other (lte).

Anybody know how to achieve a negative filter like this through a custom FilterSpec?

A: 

Won't using a "exclude" filter for the negation work?

Arthur Debert
In a normal query it would, but the Filter spec uses the format `{'key':'value'}` -> `.filter(key=value)`. Hence the problem. :)
T. Stone
oops, my bad...
Arthur Debert
+1  A: 

This feature is not part of the Django code yet; it is planned for version 1.2. You'll need to apply this patch to the Django code: http://code.djangoproject.com/ticket/5833

Use the get_query_set() method of FilterSpec. For example:

class AlunoStatus(FilterSpec):
    def __init__(self, request, params, model, model_admin):
        self.lookup_val = request.GET.get('exclude_value', None)

    def get_query_set(self, cl, qs):
        if self.lookup_val:
            qs = qs.exclude(field=self.lookup_val)
        return qs

    def choices(self, cl):
        yield {'selected': self.lookup_val is None,
               'query_string': cl.get_query_string({}, ['exclude_value']),
               'display': _('All')}
        for choice in choices:
            yield {'selected': self.lookup_val == choice,
                    'query_string': cl.get_query_string({'exclude_value': choice}),
                    'display': u"Exclude "+smart_unicode(choice)}

I didn't test this, but I hope you get the idea.

This only works on the latest SVN checkout I'm assuming?
T. Stone
Actually not even that. :) It's a "medium" priority feature for version 1.2. I'm using the patch here http://code.djangoproject.com/ticket/5833 on Django 1.0.
You know I had looked through the FilterSpec code in the django libraries and I was wondering where you were getting that from. For the moment I think I'm going to wait until it makes it into the trunk, but I'll certainly keep my eye out for this get_query_set method to become available.
T. Stone