Reputation: 16731
What is the best method for updating a model field based on the results of another model.
i.e I have the following,
from django.db import models
class ValidateResult(models.Model):
number = models.IntegerField(unique=True)
version = models.CharField(max_length=100)
class TotalResult(models.Model):
total = models.IntegerField()
What I require is TotalResults.total
to be a total count of all fields within ValidateResult.number
. I want to write this into the model so each time I update the ValidateResults
model is auto updates the totals in the TotalResult
model.
Any ideas ?
Thanks,
Upvotes: 3
Views: 2640
Reputation: 19922
You can use the signals feature:
Django includes a “signal dispatcher” which helps allow decoupled applications get notified when actions occur elsewhere in the framework. In a nutshell, signals allow certain senders to notify a set of receivers that some action has taken place. They’re especially useful when many pieces of code may be interested in the same events.
The django.db.models.signals
module predefines a set of signals sent by the model system. You could use the post_save
signal which is triggered at the end of a model's save()
method.
from django.db.models.signals import pre_save
from django.dispatch import receiver
from myapp.models import MyModel
@receiver(post_save, sender=ValidateResult)
def my_handler(sender, **kwargs):
...
Upvotes: 4