Django Admin M2M过滤列表页面上的verbose_name

时间:2011-08-26 04:05:51

标签: django admin

我有一个ManyToMany模型,我用于模型的两个字段:

class SomeModel(models.Model):
    deposit    = models.ManyToManyField(PaymentMethod, related_name="deposit")
    withdrawal = models.ManyToManyField(PaymentMethod, related_name="withdrawal")

然后在我的管理文件中,我有这个:

class SomeModelAdmin(admin.ModelAdmin):
    list_filter = ('deposit', 'withdrawal',)

唯一的问题是在列表页面上的过滤器上(在右栏中)。它说“按付款方式”,而不是“按存款”和“按提款”。

1 个答案:

答案 0 :(得分:0)

这是一个已知的错误:

https://code.djangoproject.com/ticket/15221

这是一种解决方法(适用于1.4版)。这很难看,但至少它不是猴子补丁:

from django.contrib.admin import RelatedFieldListFilter
from django.contrib.admin.util import get_model_from_relation

class WorkAroundListFilter(RelatedFieldListFilter):

    def __init__(self, field, request, params, model, model_admin, field_path):
        super(RelatedFieldListFilter, self).__init__(
            field, request, params, model, model_admin, field_path)

        other_model = get_model_from_relation(field)
        self.lookup_title = field.verbose_name
        rel_name = other_model._meta.pk.name
        self.lookup_kwarg = '%s__%s__exact' % (self.field_path, rel_name)
        self.lookup_kwarg_isnull = '%s__isnull' % (self.field_path)
        self.lookup_val = request.GET.get(self.lookup_kwarg, None)
        self.lookup_val_isnull = request.GET.get(
                                      self.lookup_kwarg_isnull, None)
        self.lookup_choices = field.get_choices(include_blank=False)
        self.title = self.lookup_title


class SomeModelAdmin(admin.ModelAdmin):
    list_filter = (
        ('deposit', WorkAroundListFilter), 
        ('withdrawal', WorkAroundListFilter),
    )