i want to write a simple django signal that would automatically change the status of a field from live to finished, when i check a button completed.
I have a model that looks like this
JavaScript
x
12
12
1
class Predictions(models.Model):
2
## other fields are here
3
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
4
status = models.CharField(choices=STATUS, max_length=100, default="in_review")
5
6
7
class PredictionData(models.Model):
8
predictions = models.ForeignKey(Predictions, on_delete=models.SET_NULL, null=True, related_name="prediction_data")
9
votes = models.PositiveIntegerField(default=0)
10
won = models.BooleanField(default=False)
11
12
when i check the won button that is in the PredictionData
model, i want to immediately changes the status
of the Prediction
to finished.
NOTE: i have some tuple at the top of the model.
JavaScript
1
8
1
STATUS = (
2
("live", "Live"),
3
("in_review", "In review"),
4
("pending", "Pending"),
5
("cancelled", "Cancelled"),
6
("finished", "Finished"),
7
)
8
Advertisement
Answer
You can make a signal with:
JavaScript
1
10
10
1
from django.db.models.signals import pre_save
2
from django.dispatch import receiver
3
4
5
@receiver(pre_save, sender=PredictionData)
6
def update_prediction(sender, instance, *args, **kwargs):
7
if instance.won and instance.predictions_id is not None:
8
prediction = self.instance.predictions
9
prediction.status = 'finished'
10
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