aggregation with f() in django rest api

from django.db.models import Count
from rest_framework.decorators import api_view
from rest_framework.response import Response
from yourapp.models import YourModel

@api_view(['GET'])
def aggregation_example(request):
    # Step 1: Perform aggregation using Django's annotate() function and Count() aggregation function.
    aggregated_data = YourModel.objects.values('category').annotate(total_count=Count('id'))

    # Step 2: Create a dictionary to hold the aggregated results.
    results = []

    # Step 3: Iterate through the aggregated data and format the results.
    for entry in aggregated_data:
        result_entry = {
            'category': entry['category'],
            'total_count': entry['total_count']
        }
        results.append(result_entry)

    # Step 4: Return the formatted results as a JSON response.
    return Response({'results': results})

This code snippet demonstrates how to perform aggregation using the annotate() function and the Count() aggregation function in a Django REST framework API view. It assumes you have a model named YourModel with a field named category that you want to aggregate based on the count of each category. The result is returned as a JSON response containing the aggregated data.