问题描述:

Here is a part of my models.py:

class College(models.Model):

name = models.CharField(max_length=100)

class MyUser(models.Model):

user = models.OneToOneField(User)

points = models.IntegerField(default=0)

college = models.ForeignKey(College, blank=True,null=True,default=None)

As you can see, a user has some points, and many users will be part of a college. Now, points of a college will be equal to sum of points of all the students in that college. So, how do I send the list of colleges to my template, and obtain their respective points ?

(I want to create a ranking page of all colleges)

网友答案:

This is a pretty standard aggregation query.

from django.db.models import Sum
colleges = College.objects.all().annotate(total_points=Sum('myuser__points'))
相关阅读:
Top