Django: как написать django сигнал для обновления поля в django?
я хочу написать простой django сигнал, который бы автоматически менял статус поля с live на finished, когда я отмечаю кнопку completed.
У меня есть модель, которая выглядит следующим образом\
class Predictions(models.Model):
## other fields are here
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
status = models.CharField(choices=STATUS, max_length=100, default="in_review")
class PredictionData(models.Model):
predictions = models.ForeignKey(Predictions, on_delete=models.SET_NULL, null=True, related_name="prediction_data")
votes = models.PositiveIntegerField(default=0)
won = models.BooleanField(default=False)
когда я проверяю кнопку won, которая находится в модели PredictionData
, я хочу немедленно изменить status
из Prediction
на finished.
ПРИМЕЧАНИЕ: у меня есть некоторый кортеж в верхней части модели.
STATUS = (
("live", "Live"),
("in_review", "In review"),
("pending", "Pending"),
("cancelled", "Cancelled"),
("finished", "Finished"),
)
Вы можете сделать сигнал с помощью:
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.
Примечание: обычно модели Django дается сингулярное имя, поэтому
Prediction
вместо.Predictions