简体   繁体   中英

how to sum in django model fields

I have two models here one is contains subject info and another one course info, i want to sum how many credits(total) have in this course,to show in template. i have tried but didn't work. thank you so much

class Course(models.Model):
    name = models.CharField(max_length=200, unique=True)
    prefix = models.CharField(max_length=20)
    code = models.CharField(max_length=20)
    subject = models.ManyToManyField('Subject', related_name='subject_list', blank=True)

def tota_credit(self):
    total = 0
    for cred in self.subject_set.all():
        total += cred.credit
    return total  # doesn't work :(


def __str__(self):
    return self.name

another model

class Subject(models.Model):
   name = models.CharField(max_length=50)
   code = models.PositiveIntegerField(unique=True)
   credit = models.IntegerField(blank=True)

def __str__(self):
    return self.name 

views.py

class Course_detail(generic.DetailView):
    model = Course
    template_name = 'course_detail.html'
    context_object_name = 'queryset'


def get_context_data(self, **kwargs):
    self.profile = Student.objects.all()
  
    context = super().get_context_data(**kwargs)
    context['profile'] = self.profile
    return context

You do not need to perform these calculations yourself. You can .annotate(…) [Django-doc] the queryset:

from django.db.models import Sum

class Course_detail(generic.DetailView):
    model = Course
    template_name = 'course_detail.html'
    queryset = Course.objects.annotate(
        
    )
    context_object_name = 'queryset'

    # …

Then you can render this with:

{{ queryset }}: {{ queryset }}
from django.db.models import Sum ... def tota_credit(self): return self.subject_set.aggregate(Sum('credit'))['credit_sum']

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