views:

635

answers:

2

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? Thanks in advance.

+11  A: 

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)
wbowers
+1  A: 

What's wrong with the following?

class Cancellation( models.Model ):
    blah
    blah
    def save( self, **kw ):
        for a in self.activity_set.all():
            a.somethingChanged( self )
        super( Cancellation, self ).save( **kw )

It would allow you to to control the notification among models very precisely. In a way, this is the canonical "Why is OO so good?" question. I think OO is good precisely because your collection of Cancellation and Activity objects can cooperate fully.

S.Lott