0

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
2
  • 1
    Hello and Welcome on Stack Overflow, can you please paste your code in your message rather than in the screenshot? Commented Nov 7, 2021 at 9:35
  • Please read this - count() in Django: docs.djangoproject.com/en/3.2/ref/models/querysets/… Commented Nov 7, 2021 at 9:36

3 Answers 3

1

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()
Sign up to request clarification or add additional context in comments.

Comments

0

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()

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.