import calendar import datetime from django.db import models from django.db.models import Sum from django.urls import reverse from django.utils import timezone class LuxSource(models.Model): name = models.CharField(max_length=200) date_recorded = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class LuxFixedMonthly(models.Model): name = models.CharField(max_length=200) source = models.ForeignKey(LuxSource, on_delete=models.CASCADE) CATEGORY = ( (0, 'Grocery & Home'), (1, 'Gas'), (2, 'Bus'), (3, 'Lodging'), (4, 'Books'), (5, 'Clothes'), (6, 'Eating Out'), (7, 'Misc'), ) category = models.IntegerField(choices=CATEGORY, default=0) date_recorded = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class LuxPurchaseStatsManager(models.Manager): def get_monthly_spending(self, month=timezone.now().month): last_day = calendar.monthrange(timezone.now().year, month)[1] start_date = datetime.date(timezone.now().year, month, 1) end_date = datetime.date(timezone.now().year, month, last_day) return self.filter(date_recorded__range=(start_date, end_date)).aggregate(Sum('amount')) def get_monthly_spending_by_category(self, cat, number_of_months=1): today = timezone.now() month = today.replace(day=1).month start_month = month - number_of_months + 1 start_date = datetime.date(timezone.now().year, start_month, 1) last_day = calendar.monthrange(timezone.now().year, month)[1] end_date = datetime.date(timezone.now().year, month, last_day) return self.filter(date_recorded__range=(start_date, end_date)).filter(category=cat).aggregate(Sum('amount')) class LuxPurchase(models.Model): amount = models.DecimalField(max_digits=6, decimal_places=2) source = models.ForeignKey(LuxSource, on_delete=models.CASCADE) CATEGORY = ( (0, 'Grocery & Home'), (1, 'Gas'), (2, 'Bus'), (3, 'Lodging'), (4, 'Books'), (5, 'Clothes'), (6, 'Eating Out'), (7, 'Misc'), ) category = models.IntegerField(choices=CATEGORY, default=0) date_recorded = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-date_recorded',) def __str__(self): return "%s - %s" %(self.amount, self.source.name) def get_absolute_url(self): return reverse("luxbudget:detail", kwargs={"pk": self.pk}) objects = models.Manager() # The default manager. stats = LuxPurchaseStatsManager()