filters.py 1.3 KB

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