filters.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. from django.contrib.admin import RelatedFieldListFilter
  2. from django.utils.encoding import smart_text
  3. from django.utils.html import format_html
  4. from django.core.urlresolvers import reverse
  5. try:
  6. from django.contrib.admin.utils import get_model_from_relation
  7. except ImportError: # Django 1.6
  8. from django.contrib.admin.util import get_model_from_relation
  9. try:
  10. from django.forms.utils import flatatt
  11. except ImportError: # Django 1.6
  12. from django.forms.util import flatatt
  13. class RelatedFieldAjaxListFilter(RelatedFieldListFilter):
  14. ajax_attrs = None
  15. def has_output(self):
  16. return True
  17. def field_choices(self, field, request, model_admin):
  18. model = field.remote_field.model if hasattr(field, 'remote_field') else field.related_field.model
  19. app_label = model._meta.app_label
  20. model_name = model._meta.object_name
  21. self.ajax_attrs = format_html('{0}', flatatt({
  22. 'data-app-label': app_label,
  23. 'data-model': model_name,
  24. 'data-ajax--url': reverse('jet:model_lookup'),
  25. 'data-queryset--lookup': self.lookup_kwarg
  26. }))
  27. if self.lookup_val is None:
  28. return []
  29. other_model = get_model_from_relation(field)
  30. if hasattr(field, 'rel'):
  31. rel_name = field.rel.get_related_field().name
  32. else:
  33. rel_name = other_model._meta.pk.name
  34. queryset = model._default_manager.filter(**{rel_name: self.lookup_val}).all()
  35. return [(x._get_pk_val(), smart_text(x)) for x in queryset]