Django 信号:检查 ManyToManyField 中的数据是否为 change/updated
Django signals: Check if the data inside of ManyToManyField is change/updated
如何在仍然访问放置 manytomanyfield 的主模型的同时检查 ManyToManyField 中的对象是否发生更改或更新。
这是代码示例:
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")
我尝试了 m2m_changed
,但只有当 students
字段上有新的 added/updated/deleted 时,它才会收到这些信号。
我想获取 Room
模型,其中学生在 students
字段中被选中。
s1 = Student.objects.first()
s1.name = "John Doe"
s1.save()
'''prints the data with Room model on it.'''
您可以为 Student
模型使用 pre_save
或 post_save
信号,访问所有 rooms
并进行一些逻辑处理。
@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
students
中的 related_name
m2m 字段可能应命名为 rooms
或 students_rooms
如何在仍然访问放置 manytomanyfield 的主模型的同时检查 ManyToManyField 中的对象是否发生更改或更新。
这是代码示例:
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")
我尝试了 m2m_changed
,但只有当 students
字段上有新的 added/updated/deleted 时,它才会收到这些信号。
我想获取 Room
模型,其中学生在 students
字段中被选中。
s1 = Student.objects.first()
s1.name = "John Doe"
s1.save()
'''prints the data with Room model on it.'''
您可以为 Student
模型使用 pre_save
或 post_save
信号,访问所有 rooms
并进行一些逻辑处理。
@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
students
中的 related_name
m2m 字段可能应命名为 rooms
或 students_rooms