Total Monthly Orders Calculation

  • Share this:

Code introduction


This function calculates the total number of orders per month. It uses Django's ORM to query the database and uses aggregate functions to calculate the total.


Technology Stack : Django ORM, Aggregate Functions, timezone

Code Type : Function

Code Difficulty : Intermediate


                
                    
import random
from django.db.models import Sum
from django.utils.timezone import now

def calculate_total_orders_by_month():
    # This function calculates the total number of orders per month
    from django.db import models
    from myapp.models import Order
    
    # Get the current year and month
    current_year = now().year
    current_month = now().month
    
    # Query to get the total number of orders for each month
    total_orders_by_month = Order.objects.annotate(
        total_orders=Sum('quantity')
    ).values(
        'order_date__month',
        'order_date__year'
    ).order_by(
        'order_date'
    )
    
    # Filter the results to only include the current month and year
    current_month_data = list(filter(lambda x: x['order_date__year'] == current_year and x['order_date__month'] == current_month, total_orders_by_month))
    
    # Return the total number of orders for the current month
    return current_month_data[0]['total_orders'] if current_month_data else 0