简体   繁体   中英

How do I create a method in django models that returns the sum of a field in that same model?

I'm new to Django and I have two models set up like this currently. I want to calculate, in the Climber model, that returns the total points that climber has earned by accessing the climbs_completed field. How can I go about doing this? In other words, how do I sum up the points for each Climb in climbs_completed ? Is there a better way to do this besides writing a method? Thank you in advance!

class Climb(models.Model):
    name = models.CharField(max_length=20, default='')
    grades = [('v'+str(i),'v'+str(i))for i in range(0,13)]
    grade = models.CharField(max_length=3, choices=grades, default='v-1')
    weeks = [(i,i)for i in range(1,13)]
    week = models.IntegerField(choices=weeks, default=0)
    points = models.IntegerField(default=0)

    def __str__(self):
        return self.name

class Climber(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    grades = [('v'+str(i),'v'+str(i))for i in range(0,13)]
    highest_grade = models.CharField(max_length=3, choices=grades, default='v0')
    team = models.ForeignKey(Team, null=True, on_delete=models.SET_NULL)
    climbs_completed = models.ManyToManyField(Climb, blank=True)

    def __str__(self):
        return self.user.username

    # for each climbs_completed, sum up the points
    def total_score(self):
        pass

You can use Sum and add the total climb points as annotated value like this:

from django.db.models import Sum

climbers = Climber.objects
print(climbers.values('pk', ))

Or you can use aggregation in the total_score method, like this:

class Climber(models.Model):
    ...

    def total_score(self):
       return self.climbs_completed.

First method is more efficient if you want to get values from bunch of climbers and do it in one database hit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM