总结请假的数量

时间:2019-12-08 20:33:35

标签: python django

我有一个具有一对多关系的模型,例如,用户可以申请一个或多个叶子。我想累加每个用户的叶子数,然后按用户分组,但是我不确定该怎么做。我做了如下操作,但似乎不起作用。

def monthly_leave_taken(request):
    result = NewLeave.objects.values('user').annotate(Sum('Total_working_days'))
    return render(request, "result.html", locals())

class NewLeave(models.Model):
    user = models.ForeignKey(User, default='', on_delete=models.CASCADE)
    leave_balances = models.ManyToManyField(Leave_Balance)
    leave = (
        ('annual', 'annual'),
        ('sick', 'sick'),

    )

    Leave_type = models.CharField(max_length=100, choices=leave, blank=False, default='')

    Start_Date = models.DateField(null=True, blank=False)
    End_Date = models.DateField(null=True, blank=False)
    Total_working_days = models.FloatField(null=True, blank=False)
    Reason = models.TextField(max_length=1000, null=True, blank=False)
    Aut = (
        ('Pending', 'Pending'),
        ('Approved', 'Approved'),
        ('Rejected', 'Rejected'),
    )
    Manager_Authorization_Status = models.CharField(max_length=100, choices=Aut, default='Pending', blank=False)
    Authorized_by_Manager = models.CharField(max_length=100, default='', blank=False)
    Authorised_Date = models.DateField(null=True, blank=False)
    DirAuth = (
        ('Pending', 'Pending'),
        ('Approved', 'Approved'),
        ('Rejected', 'Rejected'),
    )

    Director_Authorization_Status = models.CharField(max_length=100, choices=DirAuth, default='Pending', blank=False)
    Authorized_by_Director = models.CharField(max_length=100, default='', blank=False)
    Date_Authorized = models.DateField(null=True, blank=False)
    arc = (
        ('', ''),
        ('Archived', 'Archived'),

    )
    Archived = models.CharField(max_length=100, choices=arc, default='', blank=False)

    def __str__(self):
        return self.Leave_type

1 个答案:

答案 0 :(得分:1)

如果您需要用户first_name,则可能需要在User模型上运行查询。

users = User.objects.annotate(new_leave_tot_w_days=Sum('newleave__total_working_days'))

在模板中,您可以遍历用户并访问“ new_leave_tot_w_days”属性。

{%for user in users %} <td>{{user.first_name}}</td> <td>{{user.new_leave_tot_w_days}}</td> {%endfor%}