Alireza Navaie
Alireza Navaie

Reputation: 163

create a calculated field from other model's field

I'm new in django. I want to create a table that includes some fields calculated from other model's field.

class Student(models.Model):
 name = models.Charfield(max_length = 30)
 ...

class Subject(models.Model):
 student = models.ForeignKey(Student, related_name = "student_subject")
 point =  models.IntegerField(default = 0)
 ...

How can I create a queryset to get average point for each student?

Upvotes: 2

Views: 108

Answers (1)

nthall
nthall

Reputation: 2915

The relevant documentation is: https://docs.djangoproject.com/en/1.11/topics/db/aggregation/

from django.db.models import Avg

students = Student.objects.annotate(Avg('subject__point'))

Upvotes: 2

Related Questions