2011-10-09 52 views
1

如何在客戶端模型上創建一個Assigned Bankers的list_filter?使用list_filter從另一個模型中過濾FK

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

通過編寫列表類,從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, ]