On Thu, Jun 12, 2014 at 3:48 PM, Mezzy <hobbysa...@gmail.com> wrote:
> Hello
>
> How do I detect when related models have changed; If I have models such as
> the following:
>
> .. models.py
> class Model1(models.Model):
>
> field = models.CharField(max_length=255, default="Some value")
>
>
> class Model2(models.Model):
>
> field = models.CharField(max_length=255, default="Some value")
>
>
> class Model3(models.Model):
>
> field = models.CharField(max_length=255, default="Some value")
>
>
> class Model4(models.Model):
>
> one = models.OneToOneField(Model1)
>
> foreign = models.ForeignKey(Model2)
>
> many = models.ManyToManyField(Model3)
>
> counter = models.IntegerField(default=1)
>
>
>
> .. test.py
> one = Model1.objects.create()
> foreign = Model2.objects.create()
> many = [Model3.objects.create() for i in xrange(0,5)]
> x = Model2.objects.create(one=one, foreign=foreign)
> x.many = many
> x.save()
>
>
>
>
>
>
> Then I perform the following operations:
> one.field = "new value"
> one.save()
> foreign.field = "newer value"
> foreign.save()
> many[0].field = "newest value"
> many[0].save()
>
>
> How do I detect when these objects have changed? Is there a signal for this
> type of thing?
> For example if I want to increment Model4's counter field every time one of
> these objects change, what should I do?

There isn't such a signal because of the complexity (and
impossibility, in some cases) of doing so.

For instance, if a Model2 object is modified, there is potentially one
Model1 instance to signal that a related object has changed, but if a
Model3 or Model4 object is modified, potentially all Model1 instances
might require to be signalled.

There are signals for when a model instance itself changes; if you so
wish you can hook in to that and add application specific logic to
discover which Model1 instances are related to that changed instance,
and fire events for each of them.

Putting a counter on the Model1 is a denormalisation; using signals to
keep a denormalisation up to date is fragile, especially when using
django signals where there are multiple ways that data could change
without a signal firing.

Cheers

Tom

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAFHbX1K07n8ZWhEdCj-q1-eE%2BhE3PaT-5O4C5WY7bLHNjiacGg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to