使用Django的pre_delete信号创建新对象

时间:2019-03-16 15:58:54

标签: django django-models

删除Tasks实例后,我想创建一个新的Completed Tasks实例,该实例存储已删除的任务。 这是我的代码-

from django.db import models
from django.db.models.signals import post_delete, pre_delete
from django.urls import reverse, reverse_lazy
from django.contrib.auth.models import User



class Tasks(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    TaskName = models.CharField(max_length=100)
    Description = models.CharField(max_length=400)
    DueDate = models.DateField(help_text="YYYY-MM-DD")
    priority = models.IntegerField()

    def __str__(self):
        return self.TaskName

    def get_absolute_url(self):
        return reverse('tasks:detail', kwargs={'pk': self.pk})

    pre_delete.connect(lambda instance,**kwargs:CompletedTasks.obbjects.create(task = instance))


class CompletedTasks(models.Model):
    task = models.ForeignKey(Tasks, on_delete=None)

但是,它无法正常工作,没有创建CompletedTasks实例。

1 个答案:

答案 0 :(得分:0)

您不能有对不存在的对象的外键引用,建议您在Tasks模型中有一个字段来跟踪Task的状态。

类似这样的东西:

class Tasks(models.Model):
    STATUSES = (
        ('C','Completed'),
        ('A', 'Active'),
    )
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    task_name = models.CharField(max_length=100)
    description = models.CharField(max_length=400)
    due_date = models.DateField(help_text="YYYY-MM-DD")
    priority = models.IntegerField()
    status = models.CharField(max_length=1, choices=STATUSES, default='A')