Filter summary by date


(Kabiru Abdulhamid) #1

This is a report page I create which is fetching and calculating all the records.

I will like to filter by date just like how I create the form above the cards.

How can I do that?

this is my view

def report(request):
    pos = Order.objects.all().aggregate(Sum('pos'))
    pos_sum = pos['pos__sum']

    transfer = Order.objects.aggregate(Sum('transfer'))
    transfer_sum = transfer['transfer__sum']

    cash = Order.objects.aggregate(Sum('cash'))
    cash_sum = cash['cash__sum']

    total = pos_sum + transfer_sum + cash_sum

    # payments report 
    paid = Order.objects.filter(paid=True).count()
    unpaid = Order.objects.filter(paid=False).count()
    oncredit = Order.objects.filter(on_credit = True).count()
    total_payment = paid + unpaid + oncredit
    
    context = {
        'pos_sum':pos_sum,
        'transfer_sum':transfer_sum,
        'cash_sum':cash_sum,
        'total':total,
        'paid':paid,
        'unpaid':unpaid,
        'oncredit':oncredit,
        'total_payment':total_payment,
    }
    return render(request, 'customers/report_template.html', context=context)

Thanks


(Vitor Freitas) #2

Considering that your Order model have a date field, you could submit this form using GET request:

<form method="get">
  <input type="text" name="date" placeholder="mm/dd/yyyy">
  <button type="submit">Search</button>
</form>

Then on your report view:

def report(request):
    order_queryset = Order.objects.all()

    filter_date = request.GET.get('date')
    if filter_date is not None:
        order_queryset = order_queryset.filter(date=filter_date)

    pos = order_queryset.aggregate(Sum('pos'))
    pos_sum = pos['pos__sum']

    transfer = order_queryset.aggregate(Sum('transfer'))
    transfer_sum = transfer['transfer__sum']

    cash = order_queryset.aggregate(Sum('cash'))
    cash_sum = cash['cash__sum']

    total = pos_sum + transfer_sum + cash_sum

    # payments report 
    paid = order_queryset.filter(paid=True).count()
    unpaid = order_queryset.filter(paid=False).count()
    oncredit = order_queryset.filter(on_credit = True).count()
    total_payment = paid + unpaid + oncredit
    
    context = {
        'pos_sum':pos_sum,
        'transfer_sum':transfer_sum,
        'cash_sum':cash_sum,
        'total':total,
        'paid':paid,
        'unpaid':unpaid,
        'oncredit':oncredit,
        'total_payment':total_payment,
    }
    return render(request, 'customers/report_template.html', context=context)

(Kabiru Abdulhamid) #3

Thank you very much @vitor for the help.
The date filter is working, but everything is returned as None.( I catched them with 0)
what is missing?