Reputation: 965
I'm trying to setup my django administration page with HighCharts so I can allow admins to visualize some of the data easily.
I can currently get the total number of riders for all objects within the PeopleCount model (totalPeople), but when I try filtering by a StopID (totalPeopleByStop), it breaks.
Here is my models.py, along with the aforementioned methods in the PeopleCount class:
from django.db import models
from django.template.loader import render_to_string
class Vehicle(models.Model):
VehID = models.AutoField(primary_key=True)
Title = models.CharField(max_length=40)
Driver = models.CharField(max_length=25)
def __unicode__(self):
return self.Title
class Location(models.Model):
LocID = models.AutoField(primary_key=True)
VehID = models.ForeignKey('Vehicle')
Latitude = models.DecimalField(max_digits=10, decimal_places=6)
Longitude = models.DecimalField(max_digits=10, decimal_places=6)
Speed = models.DecimalField(max_digits=4, decimal_places=1)
def __unicode__(self):
#VehID + LocID Identifier
return str(self.LocID)
class PeopleCount(models.Model):
CountID = models.AutoField(primary_key=True)
StopID = models.ForeignKey('StopLocation')
VehID = models.ForeignKey('Vehicle')
LocID = models.ForeignKey('Location')
Date = models.DateField(auto_now_add=True, blank=False)
Time = models.TimeField(auto_now_add=True)
Count = models.IntegerField()
Date.editable = True
Time.editable = True
def totalPeople(self):
totPeople = 0
for model in PeopleCount.objects.all():
totPeople += model.Count
return totPeople
def totalPeopleByStop(self, stopname):
totPeople = 0
name = stopname
for model in PeopleCount.objects.filter(StopID=stopname).all():
totPeople += model.Count
return totPeople
def __unicode__(self):
return str(self.CountID)
def peoplecount_chart(self):
totalPeople = self.totalPeople()
totalRamsey = self.totalPeopleByStop("Ramsey")
lu = { 'categories' : [self.StopID],\
'tot_riders' : [self.Count],\
'tot_riders_at_stop' : [totalPeople]}
return render_to_string('admin/tracker/peoplecount/peoplecount_chart.html', lu )
peoplecount_chart.allow_tags = True
class StopLocation(models.Model):
StopID = models.AutoField(primary_key=True)
StopName = models.CharField(max_length=40)
Latitude = models.DecimalField(max_digits=10, decimal_places=6)
Longitude = models.DecimalField(max_digits=10, decimal_places=6)
def __unicode__(self):
#VehID + LocID Identifier
return str(self.StopName)
There aren't any errors that occur through django or in any logs, so I'm not entirely sure how to get totalPeopleByStop() working correctly.
Upvotes: 1
Views: 107
Reputation: 13731
You can do this a little easier with django aggregates.
from django.db.models import Sum
class PeopleCount(models.Model):
...
def totalPeopleByStop(self, stopname):
return PeopleCount.objects.filter(StopID=stopname).aggregate(
total_people_by_stop=Sum('Count'))['total_people_by_stop']
Upvotes: 1