I'm trying to make a student management website with Django. Now I want to count how many students are in a single grade and display the number in my website. How can I do that? My model:
from django.db import models
import uuid
from django.core.validators import MaxValueValidator,
MinValueValidator
# Create your models here.
class Student(models.Model):
name = models.CharField(max_length=150)
roll = models.UUIDField(default=uuid.uuid4, unique=True,
primary_key=True, editable=False)
father_name = models.CharField(max_length=150)
mother_name = models.CharField(max_length=150)
phone_number = models.IntegerField(validators=
[MaxValueValidator(99999999999)])
grade = models.ForeignKey('grade', on_delete=models.CASCADE )
def __str__(self):
return self.name
class Grade(models.Model):
grade_name = models.IntegerField(validators=
[MaxValueValidator(10), MinValueValidator(1)])
id = models.UUIDField(default=uuid.uuid4, unique=True,
primary_key=True, editable=False)
def __str__(self):
return self.grade
CodePudding user response:
if you what to group each grade without any filtering, by using following code it will group count of each group and returns it as a dict
from django.db.models import Count
Student.objects.all().order_by('id').values('grade__grade_name').annotate(count=Count('id', distinct=True))
if you want to filter a grade, the following code will return the number of students in elementary
Student.objects.filter(grade__grade_name=elementary).count()
CodePudding user response:
You can use filter()
then count()
:
first_grade_students = Student.objects.filter(grade__grade_name =1).count()
Remember using count()
is more efficient than len()
CodePudding user response:
Use django.db.models Count
like this :
from django.db.models import Count
q = Grade.objects.annotate(nb_students=Count('student'))
To access to the number of student in a Grade, do:
for grade in q:
print(grade.nb_students)