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.

37 lines
1.2 KiB

  1. from datetime import timedelta
  2. from django.contrib.auth.models import User
  3. from django.core.management.base import BaseCommand
  4. from django.db.models import Count
  5. from django.utils import timezone
  6. class Command(BaseCommand):
  7. help = """Prune old, inactive user accounts.
  8. Conditions for removing an user account:
  9. - created 1+ month ago and never logged in.
  10. Use case: visitor types in their email at the website but
  11. never follows through with login.
  12. - not logged in for 1 month, and has no checks
  13. Use case: user wants to remove their account. So they
  14. remove all checks and leave the account at that.
  15. """
  16. def handle(self, *args, **options):
  17. cutoff = timezone.now() - timedelta(days=31)
  18. # Old accounts, never logged in
  19. q = User.objects
  20. q = q.filter(date_joined__lt=cutoff, last_login=None)
  21. n1, _ = q.delete()
  22. # Not logged in for 1 month, 0 checks
  23. q = User.objects
  24. q = q.annotate(n_checks=Count("check"))
  25. q = q.filter(last_login__lt=cutoff, n_checks=0)
  26. n2, _ = q.delete()
  27. return "Done! Pruned %d user accounts." % (n1 + n2)