使用list_filter从另一个模型过滤FK

时间:2011-10-09 12:03:00

标签: django django-admin

如何在客户端模型上创建分配银行家的list_filter?

class AssignedBanker(models.Model):
    client         = models.ForeignKey(Client)
    banker         = models.ForeignKey(User)
    # ...

class Client(models.Model):
    account_name        = models.CharField(max_length=100)
    # ...

class ClientAdmin( MyModelAdmin ):
    list_filter = [ ??? ]

1 个答案:

答案 0 :(得分:1)

编写一个继承自SimpleListFilter的列表类:

from django.utils.translation import ugettext_lazy as _
from django.contrib.admin import SimpleListFilter, RelatedFieldListFilter

class AssignedBankerListFilter(SimpleListFilter):
    title = _('assignment')
    parameter_name = 'assignment'

    def lookups(self, request, model_admin):
       return AssignedBanker.objects.values_list('banker', 'banker__first_name',).distinct().order_by('banker__first_name')

    def queryset(self, request, queryset):
        if not self.value():
            return queryset
        assigned = AssignedBanker.objects.filter(banker=self.value())
        clients = [p.client.id for p in assigned]
        return queryset.filter(id__in=clients)

class ClientAdmin( MyModelAdmin ):
    list_filter = [AssignedBankerListFilter, ]