Сигнали в Django

Простенький приклад. При створенні об'єкту моделі, необхідно в автоматично створити об'єкт в сусідній моделі.

class Task(models.Model):
name = models.CharField(max_length=120)
description = models.TextField()
price = models.CharField(max_length=5)
promotional_code = models.CharField(max_length=24)
city = models.CharField(max_length=24)
is_active = models.BooleanField(default=True)
buyer = models.ForeignKey(User)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.name

class TaskStatus(models.Model):
POSTED, ASSIGNED, COMPLETED, CLOSED = range(1,5)
TASK_STATUS_VALUES = (
(POSTED, 'Posted'),
(ASSIGNED, 'Assigned'),
(COMPLETED, 'Completed'),
(CLOSED, 'Closed'),
)
task = models.ForeignKey(Task)
task_status = models.IntegerField(choices=TASK_STATUS_VALUES, blank=True, null=True)
provider = models.ForeignKey(User, blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)

def update_task_status(sender, instance, *args, **kwargs):
TaskStatus.objects.create(task=instance, task_status=1)

models.signals.post_save.connect(update_task_status, sender=Task)

Немає коментарів: