How to calculate average with Django?

django group by
django annotate
django-annotate subquery
django group by count
django group by distinct
django aggregate sum multiple fields
django group by date
django f

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 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'))

Aggregation | Django documentation, to get count, average, max, min values from a group of values/rows. Check out our blog for Django aggregate implementation with example. To know the devices which have more than two features. >>> Dev_features= device.objects.annotate(num=Count('features')).filter(num__gt=2) >>> Dev_features[0].num 3 >>>. To Know more about our Django CRM(Customer Relationship Management) Open Source Package.

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

Let's assume You have Model like this:

class Member(models.Model):
    nickname = models.CharField(max_length=16, unique=True)

class MatchResult(models.Model):
    member = models.ForeignKey('Member')
    wins = models.IntegerField()
    losses = models.IntegerField()

Now You can aggregate those using this syntax (look at __ double underscore notation):

MatchResult.objects.values(
    'username_id', 
    'username__nickname', 
    'wins',
    'losses'
).aggregate(
    user_id=F('username_id'),
    nickname=F('username__nickname'),
    avg_wins=Avg('wins'),
    avg_losses=Avg('losses')
)

Please refer to documentation.

Hint: Order of annotate and filter clauses is IMPORTANT.

Get count, average, min, max values from model field using Django , Example#. class Product(models.Model): name = models.CharField(max_length​=20) price = models.FloatField(). To Get average price of all products: >>> from  For example, you can generate the average price of all books with a title that starts with “Django” using the query: >>> Book . objects . filter ( name__startswith = "Django" ) . aggregate ( Avg ( 'price' ))

for member in Member.objects.all(): stat = MatchResult.objects.filter(member__id=member.id).aggregate(Avg('wins'))['wins__avg']

Django Aggregation

Django, Annotate the average of the created_at.time() to your queryset. After setting up a virtualenv with django installed, look in the example/ directory. Do this: Making a Simple Django App: Calculating the Distance between Two Airports Source Code for a Django App to Calculate the Distance between Any Two U.S. Airports by Oliver; 2014-06-03

django.db.models.Avg Python Example, For example, say you wanted to calculate the average price of all books available for sale. Django's query syntax provides a means for describing the set of all  The formula to calculate average is done by calculating the sum of the numbers in the list divided by the count of numbers in the list. The average of a list can be done in many ways i.e . Python Average by using the loop; By using sum() and len() built-in functions from python; Using mean() function to calculate the average from the statistics module.

django.db.models.Sum Python Example, I have created a calculated field to derived deal value. Now I'm trying to create Cost of Investment and Weighted Average Price (WAP) but no  Python mean() is an inbuilt statistics module function that used to calculate the average of numbers and list. The mean() function can be used to calculate the mean/average of the given list of numbers. It returns the mean of the data set passed as parameters. Python is a popular language when it comes to data analysis and statistics.

How to get average of time from a queryset result ? : django, Find average price across all books? from django.db.models import Avg out = Book.objects.aggregate(Avg('price')) # value of out is something  You may have to subtract the dates in python, rather than in the ORM: date1 - date2 will give you a timedelta object. Sum those and divide by the len of the list. Your calculation for cmpl_time should call Sum before dividing by Count in order to calculate the average.

Comments
  • docs.djangoproject.com/en/1.7/topics/db/aggregation
  • This does the average overall, however I need the average of each member if you understand me?
  • Yes! For example Aragorn has 34 wins and 27 losses. Jack has 2 wins and 18 losses. I need the average win rate for EACH member.
  • I think it is easier to use .values to get the wins and losses and do the calculation manually, it is simple math.
  • If someone giving -1 should explain why ?
  • Well wasn't me, but I guess because you used 'values' for no reason. aggergate get calculated in db.