Django model auto-update based on other model fields
What is the best way to update a model field based on the results of another model.
ie 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()
It requires me to TotalResults.total
be the total number of all fields inside ValidateResult.number
. I want to write this to the model, so every time I update the model ValidateResults
, it automatically updates the totals in the model TotalResult
.
Any ideas?
Thank,
source to share
You can use the signals function :
Django includes a "signal dispatcher" that allows detachable applications to receive notifications when actions take place elsewhere in the framework. In a nutshell, signals allow some senders to notify a set of receivers that some action has been taken. They are especially useful when many pieces of code might be interested in the same events.
The module django.db.models.signals
predetermines the set of signals sent by the model system. You can use a signal post_save
that is triggered at the end of the model method save()
.
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):
...
source to share