You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

56 lines
1.8 KiB

2 years ago
2 years ago
  1. from django.db.models import Count, Q, QuerySet
  2. from django_filters.rest_framework import BooleanFilter, CharFilter, FilterSet
  3. from .models import Example
  4. class ExampleFilter(FilterSet):
  5. confirmed = BooleanFilter(field_name="states", method="filter_by_state")
  6. label = CharFilter(method="filter_by_label")
  7. def filter_by_state(self, queryset, field_name, is_confirmed: bool):
  8. queryset = queryset.annotate(
  9. num_confirm=Count(
  10. expression=field_name,
  11. filter=Q(**{f"{field_name}__confirmed_by": self.request.user})
  12. | Q(project__collaborative_annotation=True),
  13. )
  14. )
  15. if is_confirmed:
  16. queryset = queryset.filter(num_confirm__gte=1)
  17. else:
  18. queryset = queryset.filter(num_confirm__lte=0)
  19. return queryset
  20. def filter_by_label(self, queryset: QuerySet, field_name: str, label: str) -> QuerySet:
  21. """Filter examples by a given label name.
  22. This performs filtering on all of the following labels at once:
  23. - categories
  24. - spans
  25. - relations
  26. - bboxes
  27. - segmentations
  28. Todo: Consider project type to make filtering more efficient.
  29. Args:
  30. queryset (QuerySet): QuerySet to filter.
  31. field_name (str): This equals to `label`.
  32. label (str): The label name to filter.
  33. Returns:
  34. QuerySet: Filtered examples.
  35. """
  36. queryset = queryset.filter(
  37. Q(categories__label__text=label)
  38. | Q(spans__label__text=label)
  39. | Q(relations__type__text=label)
  40. | Q(bboxes__label__text=label)
  41. | Q(segmentations__label__text=label)
  42. )
  43. return queryset
  44. class Meta:
  45. model = Example
  46. fields = ("project", "text", "created_at", "updated_at", "label")