1

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:

  1. Adding more students when I edit an instance of ClassSubjectGrade will add those students associated to the intermediate table

  2. Removing students from an instance of ClassSubjectGrade will remove those students associated from the intermediate table

  3. 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
K.Dᴀᴠɪs
  • 9,945
  • 11
  • 33
  • 43
mike26
  • 71
  • 3
  • 9
  • 1
    It is not really clear to me what the problem is, you do not need to do management of the `through` table, this is something Django takes care of. What exactly is not working in your project? – Willem Van Onsem Dec 09 '18 at 11:09
  • do you solve your issue please – art_cs Jul 13 '20 at 16:11

0 Answers0