In Django how do I notify a parent when a child is saved in a foreign key relationship?

前端 未结 2 900
情话喂你
情话喂你 2021-02-07 09:26

I have the following two models:

class Activity(models.Model):
    name = models.CharField(max_length=50, help_text=\'Some help.\')
    entity = models.ForeignKe         


        
2条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-07 09:52

    What you want to look into is Django's signals (check out this page too), specifically the model signals--more specifically, the post_save signal. Signals are Django's version of a plugin/hook system. The post_save signal gets sent every time a model is saved, whether it's updated or created (and it'll let you know if it was created). This is how you'd use signals to get notified when an Activity has a Cancellation

    from django.db.models.signals import post_save
    
    class Activity(models.Model):
        name = models.CharField(max_length=50, help_text='Some help.')
        entity = models.ForeignKey(CancellationEntity)
    
        @classmethod
        def cancellation_occurred (sender, instance, created, raw):
            # grab the current instance of Activity
            self = instance.activity_set.all()[0]
            # do something
        ...
    
    
    class Cancellation(models.Model):
        activity = models.ForeignKey(Activity)
        date = models.DateField(default=datetime.now().date())
        description = models.CharField(max_length=250)
        ...
    
    post_save.connect(Activity.cancellation_occurred, sender=Cancellation)

提交回复
热议问题