问题
I have table project, project has sub project and subproject has developers. Another table sprint, work distribute in sprint 1 2 ..n so on, Each sprint has different developers data. Now How can i calculate sum, current sprint value and percentage complete Using Django Orm.
Project has sub project foreign key
class project(models.Model):
title = models.CharField(max_length=150)
project = models.ForeignKey("self", on_delete=models.CASCADE,
related_name="subproject", blank=True, null=True)
Developers table
class Developers(models.Model):
quantity = models.FloatField(default=0.0)
charge_rate = models.FloatField(default=0.0)
project = models.ForeignKey("Project", on_delete=models.SET_NULL,
related_name="developers", null=True)
Table Sprint
class Sprint(models.Model):
sprint_name = models.CharField(max_length=150)
percentage = models.FloatField(default=0.0)
sprint data
class SprintsData(models.Model):
sprint = models.ForeignKey(
"project", on_delete=models.CASCADE, related_name="d",
blank=True)
percentage = models.FloatField(default=0.0)
This is sample data
project
id name project
1 development null
Sub project
id name project
1 Homepage 1
2 header 1
3 footer 1
Developers
id name quantity rate project (sub project foreign key)
1 developers 5 200 1
2 designer 5 150 2
Sprint
id name start_date end_date
1 sprint1 - -
SprintsData
id sprint project(subproject foreign key) percentage
1 1 1 5
2 1 2 80
Output looks like
sprint project sub_project total_sum percentage_complete current_sprint_amount
sprint1 development Homepage (quantity*charge_rate) 5 (total_sum)5%
sprint1 development Header 5*150 80 (5*150)*80%
回答1:
The following query will return all SprintsData
objects annotated with total_sum
and current_sprint_amount
. From this you should be able to generate your table
from django.db.models import Sum, F
SprintsData.objects.annotate(
total_sum=Sum(F('sprint__developers__quantity') * F('sprint__developers__charge_rate'), output_field=models.FloatField())
).annotate(
current_sprint_amount=F('total_sum') * F('percentage')
)
SprintsData.sprint
is actually a foreign key to the project
model which is a little confusing
The Sprint
model has no relationships to any other model so I'm not sure how you would get the sprint name
来源:https://stackoverflow.com/questions/59521332/how-to-calculate-sum-and-also-cumulative-sum-in-django-orm