1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
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()
|