#django #django-admin
#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:
Написав класс списка, который наследуется от 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, ]