簡體   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