offer_subscriptions_count.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. from optparse import make_option
  4. import datetime
  5. from django.core.management.base import BaseCommand, CommandError
  6. from django.db.models import Q, Count
  7. from coin.offers.models import Offer, OfferSubscription
  8. BOLD_START = '\033[1m'
  9. BOLD_END = '\033[0m'
  10. class Command(BaseCommand):
  11. option_list = BaseCommand.option_list + (
  12. make_option('--date', action='store', dest='date',
  13. default=datetime.date.today(), help='Specifies the date to use. Format is YYYY-MM-DD. Default is "today".'),
  14. )
  15. help = "Return subscription count for each offer type"
  16. def handle(self, *args, **options):
  17. # Get date option
  18. date = options.get('date')
  19. # Validate date type
  20. if type(date) is not datetime.date:
  21. try:
  22. datetime.datetime.strptime(date, '%Y-%m-%d')
  23. except ValueError, TypeError:
  24. raise CommandError("Incorrect date format, should be YYYY-MM-DD")
  25. # Count offer subscription
  26. offers = Offer.objects\
  27. .filter(Q(offersubscription__subscription_date__lte=date) & (Q(offersubscription__resign_date__gt=date) | Q(offersubscription__resign_date__isnull=True)))\
  28. .annotate(num_subscribtions=Count('offersubscription'))\
  29. .order_by('name')
  30. # Print count by offer type
  31. for offer in offers:
  32. self.stdout.write("{offer} offer has {count} subscriber(s)".format(
  33. offer=BOLD_START + offer.name + BOLD_END,
  34. count=BOLD_START + str(offer.num_subscribtions) + BOLD_END))