Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have the following two models:

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


class Cancellation(models.Model):
    activity = models.ForeignKey(Activity)
    date = models.DateField(default=datetime.now().date())
    description = models.CharField(max_length=250)
    ...

I would like the Activity model to be aware when a Cancellation related to it is saved (both inserted or updated).

What is the best way to go about this?

like image 464
gsiegman Avatar asked Oct 10 '08 17:10

gsiegman


1 Answers

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)
like image 81
willurd Avatar answered Oct 04 '22 04:10

willurd