Increase integer when an object is created in Django

Viewed 42

Hello I have two models Teaching Semester and Enrollments , i wanted to count the number of students in a particular course. Practically i wanted to have a registered students field which will be increased everytime when Enrollments object is created. Here is my model for Teaching Semester

class TeachingSemester(models.Model):
    department = models.ForeignKey(Department,on_delete=models.CASCADE)
    program    = models.ForeignKey(Program,on_delete=models.CASCADE)
    faculty = models.ForeignKey(FacultyData,on_delete=models.CASCADE)
    semester_choices = (
        ('Spring' , 'Spring'),
        ('Fall'   , 'Fall'),
        ('Summer'  , 'Summer')
    )
    sem_choice = models.CharField(max_length=30,choices=semester_choices,default='Spring')
    course_date      =   models.DateField(default=datetime.date.today())
    section          = models.CharField(max_length=5,default = 1)
    faculty_course     = models.ForeignKey(Course,on_delete=models.CASCADE)

And model of Enrollments

class Enrollment(models.Model):
    student = models.ForeignKey(StudentData,on_delete=models.CASCADE)
    faculty = models.ForeignKey(TeachingSemester,on_delete=models.CASCADE)
1 Answers

Please don't. It will result in a lot of trouble to keep the integer correctly updated. For example if later a StudentData is removed, it will remove all related Enrollments as well, and thus a lot of TeachingSemesters need to be updated accordingly. It can be quite hard to look for every possible scenario, and update the TeachingSemester objects accordingly.

You can .annotate(…) [Django-doc] with:

from django.db.models import Count

TeachingSemester.objects.annotate(registered_students=Count('enrollment'))

The TeachingSemester objects that arise from this QuerySet will have an extra attribute .registered_students.

Related