Search code examples
pythondjangosignals

Django signals: Check if the data inside of ManyToManyField is change/updated


how can I check if the objects inside of ManyToManyField is change or updated while still accessing the main Model where the manytomanyfield is placed.
Here is the example of code:

class Student:
    name = models.CharField(max_length=255, null=True, blank=False)
    age = models.IntegerField(default=0, null=True, blank=False)

class Room:
    students = models.ManyToManyField(Student,  related_name="list_of_students")

I tried the m2m_changed but it only recieve those signals when there's a Newly added/updated/deleted on students field.

I want to get the Room model where the student is selected at students field.

s1 = Student.objects.first()
s1.name = "John Doe"
s1.save()
'''prints the data with Room model on it.'''

Solution

  • You can use pre_save or post_save signal for Student model, access to all rooms and make some logic.

    @receiver(post_save, sender=Student)
    def handle_student_changes(sender, instance, created, **kwargs):
        if created: # check if new instance created and exit if yes
            return
        rooms = instance.list_of_students.all() # get all rooms for student
        print(rooms) # or make some other logic
    

    PS related_name in students m2m field probably should be named rooms or students_rooms