2

I want to get average of the total within the past 3 months. I have an object called 'Book' and attribute 'total'. I need to sum up the total and divide by 3 to get the avg for one month.

Here is my code:

past_3_month_avg = Book.objects.filter(trandate_b__range=(past_3_month_first_day,current_month_first_day)).aggregate(Sum('total'))

I have tried:

past_3_month_avg = Book.objects.filter(trandate_b__range=(past_3_month_first_day,current_month_first_day)).aggregate(Sum('total')/3)

It return error:

File "C:\Python\Python36\lib\site-packages\django\db\models\query.py" in aggregate
  360.                 arg.default_alias

During handling of the above exception ('CombinedExpression' object has no attribute 'default_alias'), another exception occurred:

File "C:\Python\Python36\lib\site-packages\django\core\handlers\exception.py" in inner
  34.             response = get_response(request)

File "C:\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response
  126.                 response = self.process_exception_by_middleware(e, request)

File "C:\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response
  124.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\customers\views.py" in Summary
  222.     past_3_month_avg = Book..objects.filter(trandate_b__range=(past_3_month_first_day,current_month_first_day)).aggregate(Sum('total')/3)

File "C:\Python\Python36\lib\site-packages\django\db\models\query.py" in aggregate
  362.                 raise TypeError("Complex aggregates require an alias")

Exception Type: TypeError at /summary/
Exception Value: Complex aggregates require an alias

2 Answers2

0

try

past_3_month_avg = Book.objects.filter(trandate_b__range=(past_3_month_first_day,current_month_first_day)).aggregate(sum=Sum('total'))['sum']/3

Name the result like this.

a_k_v
  • 1,558
  • 7
  • 18
0

You have to provide name to the average value in aggregate method.

past_3_month_data = Book.objects.filter(trandate_b__range(past_3_month_first_day,current_month_first_day)).aggregate(total_val_in_3_months=Sum('total'))

This will give you a dictionary containing key name 'total' and value equals Sum(total) for past 3 months.

past_3_month_avg = past_3_month_data.get('total_val_in_3_months')/3