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 LuxSpendingCategory(models.Model): name = models.CharField(max_length=200) date_recorded = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class LuxPaymentMethod(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class LuxFixedMonthly(models.Model): name = models.CharField(max_length=200) amount = models.DecimalField(max_digits=6, decimal_places=2) source = models.ForeignKey(LuxSource, on_delete=models.CASCADE) category = models.ForeignKey(LuxSpendingCategory, on_delete=models.CASCADE) payment_method = models.ForeignKey(LuxPaymentMethod, null=True, on_delete=models.CASCADE) 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): cat = LuxSpendingCategory.objects.get(name=cat) 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 = models.ForeignKey(LuxSpendingCategory, null=True, on_delete=models.CASCADE) 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()