filters.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. from django.db.models import Count
  2. from django_filters import rest_framework as filters
  3. from projects.models import Project
  4. from .models import TransactionGroup, avg_transactionevent_time
  5. class TransactionGroupFilter(filters.FilterSet):
  6. start = filters.IsoDateTimeFilter(
  7. field_name="transactionevent__created",
  8. lookup_expr="gte",
  9. label="Transaction start date",
  10. )
  11. end = filters.IsoDateTimeFilter(
  12. field_name="transactionevent__created",
  13. lookup_expr="lte",
  14. label="Transaction end date",
  15. )
  16. project = filters.ModelMultipleChoiceFilter(queryset=Project.objects.all())
  17. class Meta:
  18. model = TransactionGroup
  19. fields = ["project", "start", "end"]
  20. def filter_queryset(self, queryset):
  21. queryset = super().filter_queryset(queryset)
  22. environments = self.request.query_params.getlist("environment")
  23. if environments:
  24. queryset = queryset.filter(tags__environment__has_any_keys=environments)
  25. # This annotation must be applied after any related transactionevent filter
  26. queryset = queryset.annotate(
  27. avg_duration=avg_transactionevent_time,
  28. transaction_count=Count("transactionevent"),
  29. )
  30. return queryset