Home > Enterprise >  How to get total quantity of each kind of task in Django?
How to get total quantity of each kind of task in Django?

Time:10-24

I have 1 table for tasks, those tasks can be in 3 status"todo","in-progress" and "done", I want to calculate total number of each status' task, and put it into an array like ('todo total','progress total','done total'), any idea how can I achieve that? my final goal is to display the 3 subtotal in Chartjs, Thanks in advance.

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()

'''

CodePudding user response:

If you want to count one status by itself you can do this:

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

If you want a dictionary counting each status you can do this:

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))),
              )

or this:

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'))
        )
  • Related