我有这个模型:
#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
为什么会发生此错误?是否可以解释此错误的原因并介绍有关此错误的一些文档?
最佳答案
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
关于python - 唯一约束失败在Django中保存新obj时出错,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56248010/