如何计算具有其他公共值的所有模型对象的合计

2024-04-28 22:36:46 发布

您现在位置:Python中文网/ 问答频道 /正文

正在尝试在表中创建一个计算列,该列返回具有匹配用户id的任何db行的所有分配的\u小时数之和。当前,我在每个项的列中得到“0”。我错过了什么?谢谢你的帮助。你知道吗

注意,我使用的是django表2。你知道吗

#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')

Tags: selfprojectiddefaulttablesmodelscolumnclass
2条回答

我认为你的代码应该在表中。按用户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

谢谢你的建议。我还是很好奇有没有什么方法可以让我这样做表格.py而不是添加到我的型号.py. 我无法让它工作。你知道吗

相关问题 更多 >