使用save()

时间:2019-11-13 08:50:44

标签: django

我有以下型号:

class Employee(models.Model):
    # some fields

class EmployeeHistory(models.Model):
    employee = models.ForeignKey(Employee, on_delete=models.CASCADE)
    # some fields

我想在创建EmployeeHistory实例后立即记录新的Employee

employee = Employee(
  # some fields are filled
)
employee.save()

history = EmployeeHistory(
  employee=employee,
  # some fields are filled
)
history.save()

在这种情况下,我有两个相同的最近添加的Employee记录。我尝试删除employee.save(),但删除了save() prohibited to prevent data loss due to unsaved related object 'employee'。如何在不重复Employee的情况下保存这两个实例?

1 个答案:

答案 0 :(得分:2)

def post_save_employee_reciever(sender, instance, created, *args, **kwargs):
    if created:
        try:
            EmployeeHistory.objects.create(employee=instance)
        except:
            pass


post_save.connect(post_save_employee_reciever, sender=Employee)

您可以使用上面显示的post post信号,因此,无论何时创建Employee实例,它都会创建一个EmployeeHistory实例