Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate average with Django?

Tags:

python

django

In my Member class I have "wins" and "losses" - how do I calculate the average win rate by these 2 fields?

I can manually insert a average field and do the calculations myself, but I'm sure Django can do that for me. Any ideas?

Note: I would like the average of EACH member, not the overall average

like image 314
yaboinav Avatar asked Feb 19 '15 13:02

yaboinav


People also ask

How does Django calculate average?

You simply using values() , aggregate() and function Avg() and F() .

How do you find the average in Python?

Using Python sum() function len() function is used to calculate the length of the list i.e. the count of data items present in the list. Further, statistics. sum() function is used to calculate the sum of all the data items in the list. Note: average = (sum)/(count).

How does Django calculate percentage?

count() perc = cnt * 100 / total_count perc_dict. update( {o. value: perc} ) #after this the perc_dict will have percentages for all options that you can pass to template.

What is F in Django ORM?

In the Django QuerySet API, F() expressions are used to refer to model field values directly in the database.


1 Answers

You can use aggregate and Avg in a django query.

Supposing your model Member field names are wins and losses:

from django.db.models import Avg

Member.objects.aggregate(Avg('wins'))
Member.objects.aggregate(Avg('losses'))
like image 63
Yuri Malheiros Avatar answered Sep 24 '22 14:09

Yuri Malheiros