繁体   English   中英

如何为具有另一个公共值的所有模型对象计算总计

[英]How to calculate total for all model objects that have another common value

尝试在表中创建计算列,该表将为具有匹配user_id的任何数据库行返回所有allocate_hours的总和。 目前,我在每个项目的列中都得到“ 0”。 我在这里想念什么? 谢谢您的帮助。

请注意,我正在使用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')

我认为您的总计代码属于该表。 按user_id过滤分配,然后遍历结果查询集并求和。

我可以使用新功能解决此问题。

    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

感谢您的建议。 还是很好奇,是否有办法让我在table.py中执行此操作,而不是将其添加到我的models.py中。 我无法使它正常工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM