commit 6a328f5b06e13a25bf8a4214fe4bebfa2efe4dd7
Author: Honza Kral <Honza.Kral@gmail.com>
Date:   Fri May 8 13:19:26 2009 +0200

    New version of #3400 against [10706]
    
    Added some data to the test to actually test the filtering and just he
    fact that it works.

diff --git a/django/contrib/admin/filterspecs.py b/django/contrib/admin/filterspecs.py
index 6f643ee..7f473a2 100644
--- a/django/contrib/admin/filterspecs.py
+++ b/django/contrib/admin/filterspecs.py
@@ -15,18 +15,19 @@ import datetime
 
 class FilterSpec(object):
     filter_specs = []
-    def __init__(self, f, request, params, model, model_admin):
+    def __init__(self, f, request, params, model, model_admin, field_path=None):
         self.field = f
         self.params = params
+        self.field_path = field_path or f.name
 
     def register(cls, test, factory):
         cls.filter_specs.append((test, factory))
     register = classmethod(register)
 
-    def create(cls, f, request, params, model, model_admin):
+    def create(cls, f, request, params, model, model_admin, field_path=None):
         for test, factory in cls.filter_specs:
             if test(f):
-                return factory(f, request, params, model, model_admin)
+                return factory(f, request, params, model, model_admin, field_path=field_path)
     create = classmethod(create)
 
     def has_output(self):
@@ -52,14 +53,14 @@ class FilterSpec(object):
         return mark_safe("".join(t))
 
 class RelatedFilterSpec(FilterSpec):
-    def __init__(self, f, request, params, model, model_admin):
-        super(RelatedFilterSpec, self).__init__(f, request, params, model, model_admin)
+    def __init__(self, f, request, params, model, model_admin, field_path=None):
+        super(RelatedFilterSpec, self).__init__(f, request, params, model, model_admin, field_path=field_path)
         if isinstance(f, models.ManyToManyField):
             self.lookup_title = f.rel.to._meta.verbose_name
         else:
             self.lookup_title = f.verbose_name
-        rel_name = f.rel.get_related_field().name
-        self.lookup_kwarg = '%s__%s__exact' % (f.name, rel_name)
+        rel_name = f.rel.to._meta.pk.name
+        self.lookup_kwarg = '%s__%s__exact' % (self.field_path, rel_name)
         self.lookup_val = request.GET.get(self.lookup_kwarg, None)
         self.lookup_choices = f.get_choices(include_blank=False)
 
@@ -81,9 +82,9 @@ class RelatedFilterSpec(FilterSpec):
 FilterSpec.register(lambda f: bool(f.rel), RelatedFilterSpec)
 
 class ChoicesFilterSpec(FilterSpec):
-    def __init__(self, f, request, params, model, model_admin):
-        super(ChoicesFilterSpec, self).__init__(f, request, params, model, model_admin)
-        self.lookup_kwarg = '%s__exact' % f.name
+    def __init__(self, f, request, params, model, model_admin, field_path=None):
+        super(ChoicesFilterSpec, self).__init__(f, request, params, model, model_admin, field_path=field_path)
+        self.lookup_kwarg = '%s__exact' % self.field_path
         self.lookup_val = request.GET.get(self.lookup_kwarg, None)
 
     def choices(self, cl):
@@ -98,10 +99,10 @@ class ChoicesFilterSpec(FilterSpec):
 FilterSpec.register(lambda f: bool(f.choices), ChoicesFilterSpec)
 
 class DateFieldFilterSpec(FilterSpec):
-    def __init__(self, f, request, params, model, model_admin):
-        super(DateFieldFilterSpec, self).__init__(f, request, params, model, model_admin)
+    def __init__(self, f, request, params, model, model_admin, field_path=None):
+        super(DateFieldFilterSpec, self).__init__(f, request, params, model, model_admin, field_path=field_path)
 
-        self.field_generic = '%s__' % self.field.name
+        self.field_generic = '%s__' % self.field_path
 
         self.date_params = dict([(k, v) for k, v in params.items() if k.startswith(self.field_generic)])
 
@@ -111,14 +112,14 @@ class DateFieldFilterSpec(FilterSpec):
 
         self.links = (
             (_('Any date'), {}),
-            (_('Today'), {'%s__year' % self.field.name: str(today.year),
-                       '%s__month' % self.field.name: str(today.month),
-                       '%s__day' % self.field.name: str(today.day)}),
-            (_('Past 7 days'), {'%s__gte' % self.field.name: one_week_ago.strftime('%Y-%m-%d'),
-                             '%s__lte' % f.name: today_str}),
-            (_('This month'), {'%s__year' % self.field.name: str(today.year),
-                             '%s__month' % f.name: str(today.month)}),
-            (_('This year'), {'%s__year' % self.field.name: str(today.year)})
+            (_('Today'), {'%s__year' % self.field_path: str(today.year),
+                       '%s__month' % self.field_path: str(today.month),
+                       '%s__day' % self.field_path: str(today.day)}),
+            (_('Past 7 days'), {'%s__gte' % self.field_path: one_week_ago.strftime('%Y-%m-%d'),
+                             '%s__lte' % self.field_path: today_str}),
+            (_('This month'), {'%s__year' % self.field_path: str(today.year),
+                             '%s__month' % self.field_path: str(today.month)}),
+            (_('This year'), {'%s__year' % self.field_path: str(today.year)})
         )
 
     def title(self):
@@ -133,10 +134,10 @@ class DateFieldFilterSpec(FilterSpec):
 FilterSpec.register(lambda f: isinstance(f, models.DateField), DateFieldFilterSpec)
 
 class BooleanFieldFilterSpec(FilterSpec):
-    def __init__(self, f, request, params, model, model_admin):
-        super(BooleanFieldFilterSpec, self).__init__(f, request, params, model, model_admin)
-        self.lookup_kwarg = '%s__exact' % f.name
-        self.lookup_kwarg2 = '%s__isnull' % f.name
+    def __init__(self, f, request, params, model, model_admin, field_path=None):
+        super(BooleanFieldFilterSpec, self).__init__(f, request, params, model, model_admin, field_path=field_path)
+        self.lookup_kwarg = '%s__exact' % self.field_path
+        self.lookup_kwarg2 = '%s__isnull' % self.field_path
         self.lookup_val = request.GET.get(self.lookup_kwarg, None)
         self.lookup_val2 = request.GET.get(self.lookup_kwarg2, None)
 
@@ -159,21 +160,22 @@ FilterSpec.register(lambda f: isinstance(f, models.BooleanField) or isinstance(f
 # if a field is eligible to use the BooleanFieldFilterSpec, that'd be much
 # more appropriate, and the AllValuesFilterSpec won't get used for it.
 class AllValuesFilterSpec(FilterSpec):
-    def __init__(self, f, request, params, model, model_admin):
-        super(AllValuesFilterSpec, self).__init__(f, request, params, model, model_admin)
-        self.lookup_val = request.GET.get(f.name, None)
-        self.lookup_choices = model_admin.queryset(request).distinct().order_by(f.name).values(f.name)
+    def __init__(self, f, request, params, model, model_admin, field_path=None):
+        super(AllValuesFilterSpec, self).__init__(f, request, params, model, model_admin, field_path=field_path)
+        self.lookup_val = request.GET.get(self.field_path, None)
+        #self.lookup_choices = model_admin.queryset(request).distinct().order_by(f.name).values(f.name)
+        self.lookup_choices = model._default_manager.all().distinct().order_by(f.name).values(f.name)
 
     def title(self):
         return self.field.verbose_name
 
     def choices(self, cl):
         yield {'selected': self.lookup_val is None,
-               'query_string': cl.get_query_string({}, [self.field.name]),
+               'query_string': cl.get_query_string({}, [self.field_path]),
                'display': _('All')}
         for val in self.lookup_choices:
             val = smart_unicode(val[self.field.name])
             yield {'selected': self.lookup_val == val,
-                   'query_string': cl.get_query_string({self.field.name: val}),
+                   'query_string': cl.get_query_string({self.field_path: val}),
                    'display': val}
 FilterSpec.register(lambda f: True, AllValuesFilterSpec)
diff --git a/django/contrib/admin/validation.py b/django/contrib/admin/validation.py
index 4bef007..70d2dfc 100644
--- a/django/contrib/admin/validation.py
+++ b/django/contrib/admin/validation.py
@@ -279,7 +279,16 @@ def check_isdict(cls, label, obj):
 
 def get_field(cls, model, opts, label, field):
     try:
-        return opts.get_field(field)
+        if '__' in field:
+            f = None
+            m = model
+            path = field.split('__')
+            for field_name in path[:-1]:
+                f = model._meta.get_field(field_name)
+                model = f.rel.to
+            return opts.get_field(path[0])
+        else:
+            return opts.get_field(field)
     except models.FieldDoesNotExist:
         raise ImproperlyConfigured("'%s.%s' refers to field '%s' that is missing from model '%s'."
                 % (cls.__name__, label, field, model.__name__))
diff --git a/django/contrib/admin/views/main.py b/django/contrib/admin/views/main.py
index 98e5b9f..e444a17 100644
--- a/django/contrib/admin/views/main.py
+++ b/django/contrib/admin/views/main.py
@@ -74,9 +74,20 @@ class ChangeList(object):
     def get_filters(self, request):
         filter_specs = []
         if self.list_filter:
-            filter_fields = [self.lookup_opts.get_field(field_name) for field_name in self.list_filter]
-            for f in filter_fields:
-                spec = FilterSpec.create(f, request, self.params, self.model, self.model_admin)
+            lookup_opts = self.lookup_opts
+            for filter_name in self.list_filter:
+                if '__' in filter_name:
+                    f = None
+                    model = self.model
+                    path = filter_name.split('__')
+                    for field_name in path[:-1]:
+                        f = model._meta.get_field(field_name)
+                        model = f.rel.to
+                        f = model._meta.get_field(path[-1])
+                        spec = FilterSpec.create(f, request, self.params, model, self.model_admin, field_path=filter_name)
+                else:
+                    f = lookup_opts.get_field(filter_name)
+                    spec = FilterSpec.create(f, request, self.params, self.model, self.model_admin)
                 if spec and spec.has_output():
                     filter_specs.append(spec)
         return filter_specs, bool(filter_specs)
diff --git a/docs/ref/contrib/admin/index.txt b/docs/ref/contrib/admin/index.txt
index 700303f..263f4c2 100644
--- a/docs/ref/contrib/admin/index.txt
+++ b/docs/ref/contrib/admin/index.txt
@@ -446,6 +446,11 @@ how both ``list_display`` and ``list_filter`` work::
         list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff')
         list_filter = ('is_staff', 'is_superuser')
 
+In ``list_filter`` can be defined lookup separator as well::
+
+    class UserAdminWithLookup(UserAdmin):
+        list_filter = ('groups__name')
+
 The above code results in an admin change list page that looks like this:
 
     .. image:: _images/users_changelist.png
diff --git a/tests/regressiontests/admin_filters/__init__.py b/tests/regressiontests/admin_filters/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/tests/regressiontests/admin_filters/fixtures/admin-filter-data.json b/tests/regressiontests/admin_filters/fixtures/admin-filter-data.json
new file mode 100644
index 0000000..dd739a3
--- /dev/null
+++ b/tests/regressiontests/admin_filters/fixtures/admin-filter-data.json
@@ -0,0 +1,23 @@
+[
+    {
+        "pk": 1,
+        "model": "admin_filters.filterable",
+        "fields": {
+            "sites": [1]
+        }
+    },
+    {
+        "pk": 2,
+        "model": "admin_filters.filterable",
+        "fields": {
+            "sites": []
+        }
+    },
+    {
+        "pk": 3,
+        "model": "admin_filters.filterable",
+        "fields": {
+            "sites": [1]
+        }
+    }
+]
diff --git a/tests/regressiontests/admin_filters/fixtures/admin-filter-user.json b/tests/regressiontests/admin_filters/fixtures/admin-filter-user.json
new file mode 100644
index 0000000..33ae10e
--- /dev/null
+++ b/tests/regressiontests/admin_filters/fixtures/admin-filter-user.json
@@ -0,0 +1,20 @@
+[
+    {
+        "pk": 1,
+        "model": "auth.user",
+        "fields": {
+            "username": "admin",
+            "first_name": "",
+            "last_name": "",
+            "is_active": true,
+            "is_superuser": true,
+            "is_staff": true,
+            "last_login": "2009-03-30 22:05:28",
+            "groups": [],
+            "user_permissions": [],
+            "password": "sha1$6d71f$d2b636e70cbd76dd4138766efffc46f30bcc5895",
+            "email": "a@a.cz",
+            "date_joined": "2009-03-30 22:05:28"
+        }
+    }
+]
diff --git a/tests/regressiontests/admin_filters/models.py b/tests/regressiontests/admin_filters/models.py
new file mode 100644
index 0000000..6c28ae2
--- /dev/null
+++ b/tests/regressiontests/admin_filters/models.py
@@ -0,0 +1,14 @@
+from django.db import models
+from django.contrib.sites.models import Site
+
+class Filterable(models.Model):
+    sites = models.ManyToManyField(Site, blank=True)
+
+
+from django.contrib import admin
+
+class FilterableAdmin(admin.ModelAdmin):
+    list_filter = ('sites__domain',)
+
+admin.site.register(Filterable, FilterableAdmin)
+
diff --git a/tests/regressiontests/admin_filters/tests.py b/tests/regressiontests/admin_filters/tests.py
new file mode 100644
index 0000000..4b71c1a
--- /dev/null
+++ b/tests/regressiontests/admin_filters/tests.py
@@ -0,0 +1,22 @@
+from django.test import TestCase
+
+
+class AdminFilters(TestCase):
+    fixtures = ['admin-filter-user.json', 'admin-filter-data.json']
+    admin_url = '/test_admin/admin'
+
+    def setUp(self):
+        self.client.login(username='admin', password='admin')
+
+    def tearDown(self):
+        self.client.logout()
+
+    def test_filters_are_enabled(self):
+        """
+        log superuser in and go to filtered page
+        """
+        response = self.client.get('%s/admin_filters/filterable/' % self.admin_url, {'sites__domain': 'example.com'})
+
+        self.failUnlessEqual(response.status_code, 200)
+        self.failUnlessEqual('2 filterables' in response.content, True)
+
