IntegrityError: (1451, 'Cannot delete or update a parent row: a foreign key constraint fails (..))

IntegrityError: (1451, 'Cannot delete or update a parent row: a foreign key constraint fails (..))

删除具有 schedule_files 的用户时,我得到了这个:

IntegrityError at /admin/auth/user/166/delete/ (1451, 'Cannot delete or update a parent row: a foreign key constraint fails (vacation.vacations_schedulefile, CONSTRAINT vacations_schedulefile_user_id_e85fa52f_fk_auth_user_id FOREIGN KEY (user_id) REFERENCES auth_user (id))')

我的模型是:

class ScheduleFile(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    added = models.DateTimeField(default=django.utils.timezone.now)

    def __str__(self):
        return '[User ID: {}] {}'.format(str(self.user.id), self.user.username)

class VacationEvent(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    schedule_type = models.CharField(choices=SCHEDULE_TYPES, default=STRICT_TIME, max_length=3)
    exclude_fba_from_chatzos = models.BooleanField(default=False)
    schedule_file = models.ForeignKey(ScheduleFile, on_delete=models.CASCADE, null=True)
    status = models.CharField(verbose_name="status event", choices=EVENT_STATUSES, max_length=3, default=CREATED)

和用户(抽象用户) 我决定创建 pre_delete 信号并删除调度模型的相关对象:

@receiver(pre_delete, dispatch_uid='User')
def user_del(sender, instance, **kwargs):
    i = instance
    events = VacationEvent.objects.filter(user_id=166)
    schedule = prefetch_related_objects(events, 'schedule_file__user')
    schedule.delete()

# instance.user.schedulefile_set.clear()
# qs = VacationEvent.objects.filter(user_id=166).prefetch_related_('schedule_file')
# qs.delete()


# b = ScheduleFile.objects.filter(user_id=166)
# e = VacationEvent.objects.filter(user_id=166)
# e.schedule_file.remove(b)

但是它returns'NoneType'对象没有属性'delete'。我怎样才能做对?感谢您的帮助。

您不能删除 ScheduleFile,因为它的主键是 VacationEvent 所以你必须删除之前的 VacationEvent 记录 ScheduleFile 模型这可以通过信号或覆盖以多种方式完成 ScheduleFile 模型上的删除函数

示例:

def delete(self, using=None):
    if self.schedule_file:
        self.schedule_file.delete()
    super(ScheduleFile, self).delete(using)