唯一约束失败在Django中保存新obj时出错

时间:2019-05-22 00:58:22

标签: python django django-models django-orm

我有这个模型:

#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中使用以下代码创建新的注册时:

new_enrollment = Enrollment.objects.create(student_id=request.user.id,curriculum_id=curriculum_id)

我收到此错误:

  

唯一约束失败:lms_enrollment.student_id,   lms_enrollment.curriculum_id

为什么会发生此错误?是否可以解释此错误的原因并介绍有关此问题的一些文档?

1 个答案:

答案 0 :(得分:2)

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_together表示数据库中两个以上字段的字段不能相同

Enrollment.objects.create(student=student1, curriculum=curriculum1, payed_amount=100)
Enrollment.objects.create(student=student2, curriculum=curriculum1, payed_amount=200)
#Only curriculum is the same
Enrollment.objects.create(student=student1, curriculum=curriculum2, payed_amount=300)
#Only student is the same
Enrollment.objects.create(student=student1, curriculum=curriculum1, payed_amount=400)
#Both student and curriculum is the same with the first object,
hence it raises UNIQUE constraint failed error