如何获取Django中各类任务的总量?



我有一个任务表,这些任务可以分为三个状态:" todo "; " in-progress ";和"完成",我想要计算每个状态任务的总数,并将其放入像('todo ')这样的数组中总","进度总数","完成总数"),你知道我该怎么做吗?我的最终目标是在Chartjs中显示3小计,提前感谢。

models.py

"

class Todo(models.Model):
status_option = (
('to_do', 'to_do'),
('in_progress', 'in_progress'),
('done', 'done'),
)
status = models.CharField(max_length=20, choices=status_option, default='to_do')
# todo_list's content
team = models.ForeignKey('Team', on_delete=models.CASCADE)
project = models.ForeignKey(Project, on_delete=models.CASCADE)
name = models.CharField(max_length=20)
create_date = models.DateTimeField(auto_now_add=True)
start_date = models.DateTimeField(default=datetime.datetime.now)
due_date = models.DateTimeField(default=datetime.datetime.now)
project_code = models.CharField(max_length=20)
details = models.TextField()
def __str__(self):
return self.status
# return self.team['team'].queryset
def update_status(self):
if self.status == 'to_do':
self.status = 'in_progress'
elif self.status == 'in_progress':
self.status = 'done'
self.save()

"

如果你想单独计算一个状态,你可以这样做:

to_do_count = Todo.objects.filter(status='to_do').count()

如果你想要一个计数每个状态的字典,你可以这样做:

from django.db.models import Case, When
counts_data = Todo.objects.aggregate(
to_do_count=Count(Case(When(status='to_do', then=1))),
in_progress_count=Count(Case(When(status='in_progress', then=1))),
done_count=Count(Case(When(status='done', then=1))),
)

或:

from django.db.models import Q
counts_data = Todo.objects.aggregate(
to_do_count = Count('pk', filter=Q(status='to_do')),
in_progress_count = Count('pk', filter=Q(status='in_progress')),
done_count = Count('pk', filter=Q(status='done'))
)

相关内容

  • 没有找到相关文章

最新更新