Basically, my question is how do I implement the m2m_changed so that when I am creating, updating, or deleting an instance of ClassSubjectGrade, the intermediate table between ClassSubjectGrade and Student is also updated. Example:
Adding more students when I edit an instance of ClassSubjectGrade will add those students associated to the intermediate table
Removing students from an instance of ClassSubjectGrade will remove those students associated from the intermediate table
Deleting an instance of ClassSubjectGrade will remove all students associated with that instance
I placed my code below but I am not sure as well if I should check for those 2 actions or there is a simple way to do it. I do not get in the documentation as well how to write the code to do the things that I want whenever I am doing the 3 examples above.
class Student(models.Model):
# some fields
class ClassSubjectGrade(models.Model):
subject = models.ForeignKey(Subject, on_delete=models.CASCADE)
# other fields
students = models.ManyToManyField(Student, blank=True)
from django.db.models.signals import m2m_changed
@receiver(m2m_changed, sender=ClassSubjectGrade.students.through)
def students_changed(sender, instance, action, **kwargs):
if action == 'post_remove':
# How to remove all instances in intermediate table of
# ClassSubjectGrade and Student
# of all students that were removed from a ClassSubjectGrade
# instance?
if action == 'post_save':
# How to add instances in intermediate table of ClassSubjectGrade
# and Student
# of all students that were added from a ClassSubjectGrade instance?
class StudentGrade(models.Model):
student = models.ForeignKey(Student, on_delete=models.CASCADE)
class_subject = models.ForeignKey(ClassSubjectGrade,
on_delete=models.CASCADE)
# some fields