[英]How to calculate total for all model objects that have another common value
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. 尝试在表中创建计算列,该表将为具有匹配user_id的任何数据库行返回所有allocate_hours的总和。 Currently I am getting "0" in the column for each item.
目前,我在每个项目的列中都得到“ 0”。 What am I missing here?
我在这里想念什么? Thanks for the help.
谢谢您的帮助。
Note that I am using django tables2. 请注意,我正在使用Django table2。
#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 think your totalling code belongs in the table. 我认为您的总计代码属于该表。 Filter Allocation by user_id, then iterate over the resulting queryset and do a sum.
按user_id过滤分配,然后遍历结果查询集并求和。
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.
还是很好奇,是否有办法让我在table.py中执行此操作,而不是将其添加到我的models.py中。 I was unable to get that to work.
我无法使它正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.