tasks.py 1.1 KB

123456789101112131415161718192021222324252627282930313233
  1. from datetime import timedelta
  2. from django.conf import settings
  3. from django.utils.timezone import now
  4. from .models import Span, TransactionEvent, TransactionGroup
  5. def cleanup_old_transaction_events():
  6. """Delete older events and associated data"""
  7. days = settings.GLITCHTIP_MAX_TRANSACTION_EVENT_LIFE_DAYS
  8. days_ago = now() - timedelta(days=days)
  9. qs = Span.objects.filter(created__lt=days_ago)
  10. # Fast bulk delete - see https://code.djangoproject.com/ticket/9519
  11. qs._raw_delete(qs.db)
  12. qs = TransactionEvent.objects.filter(created__lt=days_ago)
  13. qs._raw_delete(qs.db)
  14. # Delete ~1k empty transaction groups at a time until less than 1k remain then delete the rest. Avoids memory overload.
  15. queryset = TransactionGroup.objects.filter(transactionevent=None).order_by("id")
  16. while True:
  17. try:
  18. empty_group_delimiter = queryset.values_list("id", flat=True)[
  19. 1000:1001
  20. ].get()
  21. queryset.filter(id__lte=empty_group_delimiter).delete()
  22. except TransactionGroup.DoesNotExist:
  23. break
  24. queryset.delete()