filters.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. from datetime import timedelta
  2. from django.db.models import Avg, Count
  3. from django_filters import rest_framework as filters
  4. from django.utils.timezone import now
  5. from projects.models import Project
  6. from .models import TransactionGroup
  7. class TransactionGroupFilter(filters.FilterSet):
  8. start = filters.IsoDateTimeFilter(
  9. field_name="transactionevent__created",
  10. lookup_expr="gte",
  11. label="Transaction start date",
  12. initial=now() - timedelta(days=7)
  13. )
  14. end = filters.IsoDateTimeFilter(
  15. field_name="transactionevent__created",
  16. lookup_expr="lte",
  17. label="Transaction end date",
  18. )
  19. project = filters.ModelMultipleChoiceFilter(queryset=Project.objects.all())
  20. query = filters.CharFilter(
  21. field_name="transaction",
  22. lookup_expr="icontains",
  23. label="Transaction text search",
  24. )
  25. def __init__(self, data=None, *args, **kwargs):
  26. if data is not None:
  27. data = data.copy()
  28. for name, f in self.base_filters.items():
  29. initial = f.extra.get('initial')
  30. if not data.get(name) and initial:
  31. data[name] = initial
  32. super().__init__(data, *args, **kwargs)
  33. class Meta:
  34. model = TransactionGroup
  35. fields = ["project", "start", "end"]
  36. def filter_queryset(self, queryset):
  37. queryset = super().filter_queryset(queryset)
  38. environments = self.request.query_params.getlist("environment")
  39. if environments:
  40. queryset = queryset.filter(tags__environment__has_any_keys=environments)
  41. # This annotation must be applied after any related transactionevent filter
  42. queryset = queryset.annotate(
  43. avg_duration=Avg("transactionevent__duration"),
  44. transaction_count=Count("transactionevent"),
  45. )
  46. return queryset