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
You simply using values() , aggregate() and function Avg() and F() .
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).
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.
In the Django QuerySet API, F() expressions are used to refer to model field values directly in the database.
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'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With