Home > Enterprise >  count item for months wise python DJANGO
count item for months wise python DJANGO

Time:05-14

I try to make a bar chart and I want value month wise for last 6 months

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)

here is my view.py, this count all item of last six months but I want month wise data for last six months

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

CodePudding user response:

view.py

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

index.html

{{month_count.count}}

CodePudding user response:

finally I solved this by myself and get data monthly wise, "any_variable6" mean the month before 6 month from the current month and so on

and you can also get idea how to get data from previous specific month

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)
  • Related