filters.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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. template = 'jet/related_field_ajax_list_filter.html'
  15. ajax_attrs = None
  16. def has_output(self):
  17. return True
  18. def field_choices(self, field, request, model_admin):
  19. model = field.remote_field.model if hasattr(field, 'remote_field') else field.related_field.model
  20. app_label = model._meta.app_label
  21. model_name = model._meta.object_name
  22. self.ajax_attrs = format_html('{0}', flatatt({
  23. 'data-app-label': app_label,
  24. 'data-model': model_name,
  25. 'data-ajax--url': reverse('jet:model_lookup'),
  26. 'data-queryset--lookup': self.lookup_kwarg
  27. }))
  28. if self.lookup_val is None:
  29. return []
  30. other_model = get_model_from_relation(field)
  31. if hasattr(field, 'rel'):
  32. rel_name = field.rel.get_related_field().name
  33. else:
  34. rel_name = other_model._meta.pk.name
  35. queryset = model._default_manager.filter(**{rel_name: self.lookup_val}).all()
  36. return [(x._get_pk_val(), smart_text(x)) for x in queryset]