gpt4 book ai didi

python - 在 django 中保存新对象时 UNIQUE 约束失败错误

转载 作者:行者123 更新时间:2023-12-01 07:50:21 25 4
gpt4 key购买 nike

我有这个模型:

#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)

我收到此错误:

UNIQUE constraint failed: 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 意味着数据库中超过 1 个项目的两个字段不能相同

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 中保存新对象时 UNIQUE 约束失败错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56248010/

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