gpt4 book ai didi

python - IntegrityError : (1451, '无法删除或更新父行 : a foreign key constraint fails (. 。))

转载 作者:太空宇宙 更新时间:2023-11-03 14:25:01 27 4
gpt4 key购买 nike

当使用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)

和用户(AbstractUser)我决定创建 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)

但它返回“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)

关于python - IntegrityError : (1451, '无法删除或更新父行 : a foreign key constraint fails (. 。)),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47698836/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com