filters.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. from django.contrib import admin
  2. from django.contrib.contenttypes.models import ContentType
  3. from users.models import ObjectPermission
  4. __all__ = (
  5. 'ActionListFilter',
  6. 'ObjectTypeListFilter',
  7. )
  8. class ActionListFilter(admin.SimpleListFilter):
  9. title = 'action'
  10. parameter_name = 'action'
  11. def lookups(self, request, model_admin):
  12. options = set()
  13. for action_list in ObjectPermission.objects.values_list('actions', flat=True).distinct():
  14. options.update(action_list)
  15. return [
  16. (action, action) for action in sorted(options)
  17. ]
  18. def queryset(self, request, queryset):
  19. if self.value():
  20. return queryset.filter(actions=[self.value()])
  21. class ObjectTypeListFilter(admin.SimpleListFilter):
  22. title = 'object type'
  23. parameter_name = 'object_type'
  24. def lookups(self, request, model_admin):
  25. object_types = ObjectPermission.objects.values_list('object_types__pk', flat=True).distinct()
  26. content_types = ContentType.objects.filter(pk__in=object_types).order_by('app_label', 'model')
  27. return [
  28. (ct.pk, ct) for ct in content_types
  29. ]
  30. def queryset(self, request, queryset):
  31. if self.value():
  32. return queryset.filter(object_types=self.value())