python - Average over a relationship in django -
i have 2 entities, namely project , issue defined followed:
class project(models.model): class issue(models.model): project = models.foreignkey(project, related_name='issues') progress = models.integerfield(default=0)
i'd have progress method in project model return average of related issue progress.
i tried following i'm getting related issue list.
def progress(self): return self.issues.annotate(models.avg('progress'))
thanks help.
what want is:
def progress(self): aggregate = self.issues.aggregate(models.avg('progress')) return aggregate['progress_avg']
if intend show progress of each project in project list view, use like:
for project in project.objects.annotate(progress_avg=models.avg('issues__progress')): print project.progress_avg
the latter example better list view, since avoids n+1 problem (1 aggregation query each project in list).
Comments
Post a Comment