I have ListView of projects that has tasks i want to calculate progress % of each project i have made it like this code bellow but the progress calculate all tasks even that is not related to project haw can i do it for the tasks that is related to the project
Models:
class Project(models.Model):
name = models.CharField(_("Product name"), max_length=255)
selcted_user = models.ForeignKey(
User, on_delete=models.CASCADE, limit_choices_to={'is_staff': False})
product_content = models.CharField(
_("Product content"), max_length=255)
order_number = models.CharField(
_("Order number"), max_length=255)
amount = models.FloatField(_("Amount $"))
product_image = models.ImageField(
_("Product image"), upload_to="projects/%Y/%m/%d/", default='default-thumb.png')
date = models.DateTimeField(auto_now_add=True)
class Status(models.TextChoices):
WORKING = '1', 'Working'
DONE = '2', 'Done'
PENDING = '3', 'Pending'
status = models.CharField(
max_length=7, choices=Status.choices, default=Status.WORKING)
class Meta:
ordering = ['name']
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('project-detail', kwargs={'pk': self.pk})
class Task(models.Model):
name = models.CharField(max_length=255)
project = models.ForeignKey(
Project, on_delete=models.CASCADE, related_name='task_project')
class Done(models.TextChoices):
NO = '1', 'No'
WORKING = '2', 'Working'
YES = '3', 'Yes'
is_done = models.CharField(
max_length=3, choices=Done.choices, default=Done.WORKING)
class Meta:
ordering = ['project', 'name']
def __str__(self):
return self.name
Review the examples in the docs. Try using the shell to experiment with some queries. If you get stuck with a particular element, post here what you’ve tried and we’ll see if we can help.
Since you haven’t posted your models, it’s tough to provide an accurate example, but as a starting point you should be able to play with: project_queryset = Project.objects.annotate(task_count=Count('task'))
This should create an attribute in each element of project_queryset called task_count which contains the number of tasks associated with that project.
It still calculates all the tasks even if they are unrelated to the project.
And what I need is to calculate the percentage of tasks that are done for each project alone in the list view of the projects.
hi again, will I did this code and it works fin in terminal it give me the result that i want
project = Project.objects.all()
task = Task.objects.all()
for t in task:
for p in project:
if t.project.id == p.id:
if t.is_done == '3':
all_project = p.id
total_progress = task.filter(project_id=all_project, is_done='3').count() * 100 / task.filter(project_id=all_project).count()
print(t.name, p.id, total_progress)
else:
context['progress_done'] = 0
now I want to render this in the template like the code above haw can I do it