Django-Admin:UserProfile的list_filter属性

tba*_*ack 7 django django-admin

我想允许我的网站管理员过滤管理站点上特定国家/地区的用户.所以自然要做的就是这样:

#admin.py
class UserAdmin(django.contrib.auth.admin.UserAdmin):
    list_filter=('userprofile__country__name',)

#models.py
class UserProfile(models.Model)
    ...
    country=models.ForeignKey('Country')

class Country(models.Model)
    ...
    name=models.CharField(max_length=32)
Run Code Online (Sandbox Code Playgroud)

但是,由于在django中处理用户及其UserProfile的方式,这会导致以下错误:

'UserAdmin.list_filter[0]' refers to field 'userprofile__country__name' that is missing from model 'User'
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个限制?

Clé*_*ent 10

您正在寻找的是自定义管理FilterSpecs.坏消息是,对这些人的支持可能不会很快发布(你可以在这里跟踪讨论).

但是,以肮脏的黑客为代价,您可以解决这个限制.FilterSpecs在潜入代码之前如何构建一些亮点:

  • 构建FilterSpec要在页面上显示的列表时,Django会使用您提供的字段列表list_filter
  • 这些字段必须是模型上的真实字段,而不是反向关系,也不是自定义属性.
  • Django维护一个FilterSpec类列表,每个类都与一个测试函数相关联.
  • 对于每个字段list_filter,Django将使用测试函数为该字段返回True的第一个FilterSpec类.

好的,现在考虑到这一点,请看下面的代码.它改编自django片段.代码的组织由您自行决定,请记住,应该由admin应用程序导入.

from myapp.models import UserProfile, Country
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin

from django.contrib.admin.filterspecs import FilterSpec, ChoicesFilterSpec
from django.utils.encoding import smart_unicode
from django.utils.translation import ugettext_lazy as _

class ProfileCountryFilterSpec(ChoicesFilterSpec):
    def __init__(self, f, request, params, model, model_admin):
        ChoicesFilterSpec.__init__(self, f, request, params, model, model_admin)

        # The lookup string that will be added to the queryset
        # by this filter
        self.lookup_kwarg = 'userprofile__country__name'
        # get the current filter value from GET (we will use it to know
        # which filter item is selected)
        self.lookup_val = request.GET.get(self.lookup_kwarg)

        # Prepare the list of unique, country name, ordered alphabetically
        country_qs = Country.objects.distinct().order_by('name')
        self.lookup_choices = country_qs.values_list('name', flat=True)

    def choices(self, cl):
        # Generator that returns all the possible item in the filter
        # including an 'All' item.
        yield { 'selected': self.lookup_val is None,
                'query_string': cl.get_query_string({}, [self.lookup_kwarg]),
                'display': _('All') }
        for val in self.lookup_choices:
            yield { 'selected' : smart_unicode(val) == self.lookup_val,
                    'query_string': cl.get_query_string({self.lookup_kwarg: val}),
                    'display': val }

    def title(self):
        # return the title displayed above your filter
        return _('user\'s country')

# Here, we insert the new FilterSpec at the first position, to be sure
# it gets picked up before any other
FilterSpec.filter_specs.insert(0,
  # If the field has a `profilecountry_filter` attribute set to True
  # the this FilterSpec will be used
  (lambda f: getattr(f, 'profilecountry_filter', False), ProfileCountryFilterSpec)
)


# Now, how to use this filter in UserAdmin,
# We have to use one of the field of User model and
# add a profilecountry_filter attribute to it.
# This field will then activate the country filter if we
# place it in `list_filter`, but we won't be able to use
# it in its own filter anymore.

User._meta.get_field('email').profilecountry_filter = True

class MyUserAdmin(UserAdmin):
  list_filter = ('email',) + UserAdmin.list_filter

# register the new UserAdmin
from django.contrib.admin import site
site.unregister(User)
site.register(User, MyUserAdmin)
Run Code Online (Sandbox Code Playgroud)

它显然不是灵丹妙药,但它会完成工作,等待更好的解决方案出现.(例如,一个将子类化ChangeList和覆盖的get_filters).