[Answered ]-Django: how to write django signal to update field in django?

1👍

You can make a signal with:

from django.db.models.signals import pre_save
from django.dispatch import receiver


@receiver(pre_save, sender=PredictionData)
def update_prediction(sender, instance, *args, **kwargs):
    if instance.won and instance.predictions_id is not None:
        prediction = self.instance.predictions
        prediction.status = 'finished'
        prediction.save(update_fields=('status',))

Note: Signals are often not a robust mechanism. I wrote an article [Django-antipatterns] that discusses certain problems when using signals. Therefore you should use them only as a last resort.


Note: normally a Django model is given a singular name, so Prediction instead of Predictions.

Leave a comment