Reputation: 977
I have this model:
#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"),)
and when I want to create new enrollment in my views.py
with this codes:
new_enrollment = Enrollment.objects.create(student_id=request.user.id,curriculum_id=curriculum_id)
I got this error:
UNIQUE constraint failed: lms_enrollment.student_id, lms_enrollment.curriculum_id
Why this error happened? Is it possible to explain the cause of this error and introduce some documentations about that?
Upvotes: 1
Views: 1139
Reputation: 2982
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 means that both of the fields can't be same for more than 1 item in the database
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
Upvotes: 1