Django 计算每月收入和费用
您好开发者如何用日期计算收入。例如上个月收入去年收入和本月收入 models.pyDjango 计算每月收入和费用,django,Django,您好开发者如何用日期计算收入。例如上个月收入去年收入和本月收入 models.py class Add(models.Model): income = models.IntegerField(blank=True, null=True) expense = models.IntegerField(default=0) date = models.DateTimeField(default=timezone.now, null=True, blank=True) 您可以使
class Add(models.Model):
income = models.IntegerField(blank=True, null=True)
expense = models.IntegerField(default=0)
date = models.DateTimeField(default=timezone.now, null=True, blank=True)
您可以使用将日期截断为月初。然后我们可以说明:
from django.db.models import Sum
from django.db.models.functions import TruncMonth
Add.objects.annotate(
month=TruncMonth('date')
).values('month').annotate(
total_income=Sum('income'),
total_expense=Sum('expense')
).order_by('month')
这将返回一个包装字典的查询集,例如:
<QuerySet [
{'month': datetime(2019, 1, 1), 'total_income': 123, 'total_expense': 456},
{'month': datetime(2019, 2, 1), 'total_income': 450, 'total_expense': 321}
]>
您可以使用将日期截断为月初。然后我们可以说明:
from django.db.models import Sum
from django.db.models.functions import TruncMonth
Add.objects.annotate(
month=TruncMonth('date')
).values('month').annotate(
total_income=Sum('income'),
total_expense=Sum('expense')
).order_by('month')
这将返回一个包装字典的查询集,例如:
<QuerySet [
{'month': datetime(2019, 1, 1), 'total_income': 123, 'total_expense': 456},
{'month': datetime(2019, 2, 1), 'total_income': 450, 'total_expense': 321}
]>
您可以使用“截断”函数,如TruncMonth、TruncDay、TruncYear。 代码示例:
from django.db.models.functions import TruncMonth
from django.db.models import Sum
Add.objects
.annotate(month=TruncMonth('date')) # Truncate to month and add to select list
.values('month') # Group By month
.annotate(income_sum=Sum('income'),expense_sum=Sum('expense')) # Select the count of the grouping
.values('month', 'income_sum','expense_sum')
您可以使用“截断”函数,如TruncMonth、TruncDay、TruncYear。 代码示例:
from django.db.models.functions import TruncMonth
from django.db.models import Sum
Add.objects
.annotate(month=TruncMonth('date')) # Truncate to month and add to select list
.values('month') # Group By month
.annotate(income_sum=Sum('income'),expense_sum=Sum('expense')) # Select the count of the grouping
.values('month', 'income_sum','expense_sum')
你试过什么?你读过吗?没有读过。你试过什么?你读过吗?没有,我没读过。