Подсчет элементов по месяцам мудрый питон DJANGO

Я пытаюсь построить гистограмму и хочу получить значение по месяцам за последние 6 месяцев

my models.py

class Btdetail(models.Model):
    id = models.IntegerField(primary_key=True)
    BatType = models.CharField(max_length=200, default=1)
    MaxVolt = models.IntegerField()
    DatePurchase = models.DateTimeField(auto_now_add=True)
    Manf_ID = models.CharField(max_length=200)

вот мой view.py, он считает все элементы за последние шесть месяцев, но мне нужны данные по месяцам за последние шесть месяцев

def index_view(request):
    months_before = 5
    now = datetime.utcnow()
    from_datetime = now - relativedelta(months=months_before)
    modified_from_datetime = from_datetime.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
    month_count = Btdetail.objects.filter(DatePurchase__gte=modified_from_datetime).count()
    return render(request, "index.html", {'month_count': month_count})

view.py

month_count = Btdetail.objects.filter(DatePurchase__gte=modified_from_datetime)

index.html

{{month_count.count}}

В итоге я решил эту проблему самостоятельно и получил данные по месяцам, "any_variable6" означает месяц до 6 месяца от текущего месяца и так далее

и вы также можете получить представление о том, как получить данные за предыдущий конкретный месяц

from datetime import datetime
from dateutil.relativedelta import relativedelta

def index_view(request, x=0, y=0):

    now = datetime.now()
    month6 = now - relativedelta(months=5)
    modified6 = month6.replace(day=1)
    month5 = now - relativedelta(months=4)
    modified5 = month5.replace(day=1)
    month4 = now - relativedelta(months=3)
    modified4 = month4.replace(day=1)
    month3 = now - relativedelta(months=2)
    modified3 = month3.replace(day=1)
    month2 = now - relativedelta(months=1)
    modified2 = month2.replace(day=1)
    month1 = now - relativedelta(months=0)
    modified1 = month1.replace(day=1)
    mon6 = Btdetail.objects.filter(DatePur__range=[modified6, modified5]).count()
    mon5 = Btdetail.objects.filter(DatePur__range=[modified5, modified4]).count()
    mon4 = Btdetail.objects.filter(DatePur__range=[modified4, modified3]).count()
    mon3 = Btdetail.objects.filter(DatePur__range=[modified3, modified2]).count()
    mon2 = Btdetail.objects.filter(DatePur__range=[modified2, modified1]).count()
    mon1 = Btdetail.objects.filter(DatePur__range=[modified1, now]).count()

    context = {
        'mon6': mon6,
        'mon5': mon5,
        'mon4': mon4,
        'mon3': mon3,
        'mon2': mon2,
        'mon1': mon1
    }
return render(request, "index.html", context)
Вернуться на верх