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