2014-05-13 2 views
0

부모 개체의 modification_date을 최신으로 유지하는 데 문제가 있습니다. 부모의 modification_date 필드가 하위의 modification_date 필드와 동시에 업데이트되기를 원합니다.두 모델을 동시에 다른 모델로 업데이트

class Parent(models.Model): 
    modification_date = models.DateTimeField(auto_now=True) 
    note = models.ManyToManyField('Child') 

class Child(models.Model): 
    modification_date = models.DateTimeField(auto_now=True) 
    content = models.TextField() 

저는 장고를 사용하고 있습니다.

답변

1

post_save 신호 기능을 사용합니다. 따라서 하위 모델을 업데이트 할 때마다 해당 함수가 트리거되고 상위 모델을 변경할 수 있습니다.

from django.db.models.signals import post_save 

# method for updating 
def update_parent(sender, instance, **kwargs): 
    parent = Parent.object.get() #the parent you need to update 
    parent.modification_date = instance.modification_date 
    parent.save() 

# register the signal 
post_save.connect(update_parent, sender=Child) 
관련 문제