django models relations getting count of given tasks
Trying to fetch a function from a table that is supposed to be there, but cannot get the value. Trying to get the amount of task that is completed.
models.py
class Task(models.Model):
title = models.CharField(max_length=55, null=True, blank=True)
slug = models.SlugField(max_length=500, unique=True, blank=True)
task_completed = models.BooleanField(default=False)
description = models.TextField(default="Task description")
start_date = models.DateTimeField()
due_date = models.DateTimeField()
checklist = models.ManyToManyField(Checklist, blank=True)
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super(Task, self).save(*args, **kwargs)
def get_url(self):
return reverse('checklists', kwargs={
'slug':self.slug
})
def __str__(self):
return self.title
@property
def num_task_completed(self):
return self.task_completed.count()
class Project(models.Model):
project_manager = models.ForeignKey(Profile, on_delete=CASCADE)
title = models.CharField(max_length=55, null=True, blank=True)
developers = models.ManyToManyField(Profile, related_name='projects')
slug = models.SlugField(max_length=500, unique=True, blank=True)
description = models.TextField(default="Project description")
date = models.DateTimeField(auto_now_add=True)
start_date = models.DateTimeField()
due_date = models.DateTimeField()
tasks = models.ManyToManyField(Task, blank=True)
teams = models.ManyToManyField(Team, blank=True)
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super(Project, self).save(*args, **kwargs)
def get_url(self):
return reverse('project_detail', kwargs={
'slug':self.slug
})
def __str__(self):
return self.title
@property
def num_task(self):
return self.tasks.count()
Then in the html is just loop through all projects
{% for projects in projects.all %}
<span class="text-small"> {{ projects.tasks.num_task_completed }} /{{ projects.num_task }}</span>
I manage to get the amount of tasks, but not the amount completed.
Solution 1:
Use self.tasks.filter(task_completed = True).count()
to get the number of completed tasks in a project.