Django 查询过去 6 个月的月份

Django Query month wise with last 6 month

我正在查询,组是最近6个月的订单。

这是我的模型:

class Order(models.Model):
    created_on = models.DateTimeField(_("Created On"), auto_now_add=True)

这是我解析月份的方法:

from django.db.models import Func
class Month(Func):
    """
        Method to extract month
    """
    function = 'EXTRACT'
    template = '%(function)s(MONTH from %(expressions)s)'
    output_field = models.IntegerField()

这是我的查询:

        current_date = date.today()
        months_ago = 6
        six_month_previous_date = current_date - timedelta(days=(months_ago * 365 / 12))

        order = Order.objects.filter(
            created_on__gte=six_month_previous_date,
        ).annotate(
            month=Month('created_on')
        ).values(
            'month'
        ).annotate(
            count=Count('id')
        ).values(
            'month',
            'count'
        ).order_by(
            'month'
        )

在我的数据库order table中,只有条目: 所以它是 returning

[{'month': 10, 'count': 1}]

但我不想要这样,我想要过去 6 个月的这些,如果一个月内没有销售,它应该 return count: 0

像下面这样:

       [
            {'month': 10, 'count': 1},
            {'month': 9, 'count': 0}
            {'month': 8, 'count': 0}
            {'month': 7, 'count': 0}
            {'month': 6, 'count': 0}
            {'month': 5, 'count': 0}
        ]

数据库在封闭世界假设 下工作,因此它不会插入具有0 的行。但是,您可以 post-process 列表。

from django.utils.timezone import <b>now</b>

order = Order.objects.filter(
    created_on__gte=six_month_previous_date,
).values(
    month=Month('created_on')
).annotate(
    count=Count('id')
).order_by('month')

order = {r['month']: r['count'] for r in order}

month = now().month
result = [
    {'month': <b>(m % 12)+1</b>, 'count': <b>order.get((m % 12) + 1, 0)</b>}
    for m in range(month-1, month-8, -1)
]

请注意,Django 已经 一个 ExtractMonth function [Django-doc]