Nick T
Nick T

Reputation: 683

How to get the sum of a field in Django

How would I render the total for values of a particular field? As you can see I am using reverse relations here because I have a foreign key (I'm not sure if that makes a difference). For instance what would I do if I wanted the total of the values in the 'ab' field. I know I have to use aggregate or annotate method. What would that look like in my particular situation?

models.py

class Batting(models.Model):
    id = models.IntegerField(db_column='ID', primary_key=True)
    playerid = models.ForeignKey('PlayerLkup', models.DO_NOTHING, db_column='playerID', blank=True, null=True)
    g = models.IntegerField(db_column='G', blank=True, null=True
    ab = models.IntegerField(db_column='AB', blank=True, null=True)
    year = models.IntegerField(db_column='Year', blank=True, null=True) 
    complete_name = models.CharField(max_length=50, blank=True, null=True)

class PlayerLkup(models.Model):
    playerid = models.CharField(db_column='playerID', primary_key=True, max_length=255)
    birthday = models.IntegerField(db_column='birthDay', blank=True, null=True)
    namefirst = models.CharField(db_column='nameFirst', max_length=255, blank=True, null=True)
    namelast = models.CharField(db_column='nameLast', max_length=255, blank=True, null=True)

views.py

from django.shortcuts import render
from .models import PlayerLkup


def player_info(request, playerid):
    playerdata = PlayerLkup.objects.get(playerid=playerid)
    battingstats = playerdata.batting_set.all()
    return render(request, 'careerstats/playerpage.html', {'playerdata': playerdata, 'battingstats': battingstats})

Upvotes: 2

Views: 685

Answers (4)

crappy_hacker
crappy_hacker

Reputation: 301

player = PlayerLkup.objects.get(playerid='FILL IN ID OF PLAYER HERE')
player_abs = Batting.objects.filter(playerid=player).values('ab')

I'm pretty sure you don't need to perform any operation like SUM or COUNT to simply retrieve a value.

Also, you may be confusing Foreign Key and Many to Many...

Your view could simply have this:

def player_info(request, playerid):
    player = PlayerLkup.objects.get(playerid=playerid)
    player_stats = Batting.objects.get(playerid=player)
    player_abs = player_stats.ab
    # below line should be same value as above
    player_abs = Batting.objects.filter(playerid=player).values('ab')
    context = {
        'player': player,
        'player_stats': player_stats,
        'player_abs': player_abs
    }
    return render(request,'careerstats/playerpage.html', context)

Upvotes: 1

Sushant
Sushant

Reputation: 3669

There's an annotate example in the documentation that might fit here -

total_ab = PlayerLkup.objects.get(playerid=playerid).annonate(total_ab=Sum('batting__ab'))

(Warning!) I have not tested this.

Look at the example here for more information.

Upvotes: 0

NS0
NS0

Reputation: 6096

You could try to aggregate in the following way

from django.db.models import Sum
result = Batting.objects.aggregate(sum_of_ab=Sum("ab"))
print result["sum_of_ab"]

To get all the sum of all ab fields that are associated with a particular player, you can modify the query to filter first

from django.db.models import Sum

playerdata = PlayerLkup.objects.get(playerid=playerid)
result = Batting.objects.filter(playerid=playerdata).aggregate(sum_of_ab=Sum("ab"))
print result["sum_of_ab"]

Upvotes: 2

Jay
Jay

Reputation: 1309

Is this what you mean? The sum of all AB integers for each object in the Batting model?

from django.shortcuts import render
from .models import PlayerLkup, Batting


def player_info(request, playerid):
    count = 0
    foo = Batting.objects.filter(playerid=playerid)
    for x in foo:
        count += int(x.ab)
    return render(request, 'careerstats/playerpage.html', {'playerdata': playerdata, 'battingstats': battingstats, 'count':count})

Upvotes: 0

Related Questions