Search code examples
pythondjangoparent

Updating two field from different models simultaneously


I have a problem with keeping the Parent object's modification_date up to date. I want the Parents's modification_date field to update simultaneously with the Child's modification_date field.

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()

I am using Django.


Solution

  • I would do a post_save signal function. So everytime you update Child Model it will trigger that function and you can change the Parent model:

    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)