Trying to create a calculation column in a table where it returns the sum of all allocated_hours for any db row that has a matching user_id. Currently I am getting "0" in the column for each item. What am I missing here? Thanks for the help.
Note that I am using django tables2.
#model.py
class Allocation(models.Model):
user_id = models.ForeignKey(Resource)
project_id = models.ForeignKey(Project)
week = models.DateField(default=timezone.now)
allocated_hours = models.IntegerField(default=0)
actual_hours = models.IntegerField(default=0)
def __str__(self):
return '%s - %s' % (self.user_id, self.project_id)
def allocation_total(self):
alltotal = 0
for i in Allocation.objects.values_list('user_id'):
if i == Allocation.user_id:
alltotal += Allocation.allocated_hours
return alltotal
-
#tables.py
class Project_Resource_table(tables.Table):
role = tables.Column(accessor='user_id.resource_type')
name = tables.Column(accessor='user_id.resource_name')
allocation = tables.Column(accessor='allocation_total')
class Meta:
model = Allocation
exclude = ('id', 'user_id', 'project_id', 'week', 'allocated_hours', 'actual_hours')
sequence = ('role', 'name', 'allocation')
I was able to work around the issue with a new function.
def total_allocation(self):
a = Allocation.objects.filter(project_id=self.project_id)
total = 0
for i in a:
if i.user_id == self.user_id:
total += i.allocated_hours
return total
Thanks for the suggestions. Still curious if there is a way for me to do this in tables.py rather than adding it to my models.py. I was unable to get that to work.