"Django保存新对象时出现唯一约束失败错误"

2024-05-12 15:52:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个型号:

#models.py
class Enrollment(models.Model):
    student = models.ForeignKey(User, on_delete=models.PROTECT)
    curriculum = models.ForeignKey(Curriculum, on_delete=models.PROTECT)
    enrolment_date = models.DateTimeField(null=True,blank=True,auto_now_add=True)
    payed_amount = models.PositiveIntegerField(null=True,blank=True)
    is_complete_paid = models.BooleanField(null=True,blank=True,default=False)

    class Meta:
        unique_together = (("student", "curriculum"),)

当我想用以下代码在我的views.py中创建新注册时:

^{pr2}$

我有个错误:

UNIQUE constraint failed: lms_enrollment.student_id, lms_enrollment.curriculum_id

为什么会发生这个错误?是否可以解释此错误的原因并介绍一些相关文档?在


Tags: pytrueonmodels错误protectdeletenull
1条回答
网友
1楼 · 发布于 2024-05-12 15:52:49
class Enrollment(models.Model):
    student = models.ForeignKey(User, on_delete=models.PROTECT)
    curriculum = models.ForeignKey(Curriculum, on_delete=models.PROTECT)
    payed_amount = models.PositiveIntegerField(null=True, blank=True)

    class Meta:
        unique_together = (("student", "curriculum"),)

在Meta.unique一起这意味着数据库中的两个字段不能超过1

^{pr2}$

相关问题 更多 >