I'm writing a REST API using Django and Django Rest Framework. I'm currently writing the models.
I have a model for students, a model for questions and a model for answers.
class Question(models.Model): question_text = models.CharField() class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) answer_text = models.CharField() class Student(models.Model): name = models.CharField() The students should be able to pick one and only one answer per question. So I was thinking of designing a student picked answer model - so that I can let the students pick through a relation - like this:
class StudentPickedAnswer(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) answer = models.ForeignKey(Answer, on_delete=models.CASCADE) I found that there is a unique_together constraint for the class Meta. But it seems to me that it can't specify relations. I would need something like this;
class Meta: unique_together = ('student', 'answer__question') How can I achieve that the students can only pick one question per answer? Or is picking through a model with relations a bad design?
unique_togetheris specified at database level, and this does not know anything about relations, so no, you can not look "through" foreign keys.validatemethods.