Home > Enterprise >  Django queryset for current year
Django queryset for current year

Time:03-31

I have my query written to get some thing from database and display on my website that query is getting all the data from db but what if i want to get the data particular to current year only

def get(self, request, *args, **kwargs):
    filters = self.get_filters()

    result = Model.objects.all().filter(*filters).distinct().aggregate(
        t=Sum('t'),
        b=Sum('b'),
    )

    result2 = Model.objects.all().filter(*filters).distinct().aggregate(
        past_due=Sum('balance', filter=Q(due_date__lt=timezone.now()))
    )

    zero = Decimal('0.00')

    total = result['t'] or zero
    balance = result['b'] or zero
    past_due = result2['past_due'] or zero
    amount_received = t - b

CodePudding user response:

I think filter=Q(due_date__year=datetime.now().date().year) should work for you, if I understand your question correctly.

CodePudding user response:

This worked for me

result = Model.objects.all().filter(*filters, created__year=datetime.now().year).distinct().aggregate(
            t=Sum('t'),
            b=Sum('b'),
        )
    
        result2 = Model.objects.all().filter(*filters, created__year=datetime.now().year).distinct().aggregate(
            past_due=Sum('balance', filter=Q(due_date__lt=timezone.now()))
        )
  • Related