Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Django 计算每月收入和费用_Django - Fatal编程技术网

Django 计算每月收入和费用

Django 计算每月收入和费用,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) 您可以使

您好开发者如何用日期计算收入。例如上个月收入去年收入和本月收入

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)
您可以使用将日期截断为月初。然后我们可以说明:

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')  

你试过什么?你读过吗?没有读过。你试过什么?你读过吗?没有,我没读过。