Home > Blockchain >  how to make primay or unique three field in django models?
how to make primay or unique three field in django models?

Time:09-27

I have the four models in my Django models.py ( User, Exam, Questions, Answers ) the Answer model has four fields ( user, exam, question, answer) after creating an exam and creating questions for that, the users come to take an exam I want to store the user's answers in the Answer model, therefore, I specify which user is taking which exam and answering which question, at the end I save the user's answers in the last field ( the 'answer' field in Answer modle )

but I want this user only once can answer this question in this exam, so I want to make these fields ( user, exam, question ) primary in the Answer model that

my Answer model:

class Answer(models.Model):
    exam      = models.ForeignKey(Exam, on_delete=models.CASCADE, default=None)
    user      = models.ForeignKey(User, on_delete=models.CASCADE)
    question  = models.ForeignKey(Question, on_delete=models.CASCADE)
    answer    = models.CharField(max_length=8)

I don't know how to do this action to primary three field actually, there is no matter whether the two or one fields of these three fields are similar, I just want to prevent storing records that user, exam, and question fields are already stored

for example, I have this record in my database: user:1, exam:52, question:38, answer: "option_a"

when I want to store the following record I expect to get an error: user:1, exam:52, question:38, answer:"option_b"

but this record is ok: user:1, exam:52, question:60, answer:"option_c"

CodePudding user response:

Django want only one field as primary key. The solution in your case is to use unique_together for your three fields:

class Answer(models.Model):
    exam      = models.ForeignKey(Exam, on_delete=models.CASCADE, default=None)
    user      = models.ForeignKey(User, on_delete=models.CASCADE)
    question  = models.ForeignKey(Question, on_delete=models.CASCADE)
    answer    = models.CharField(max_length=8)

    class Meta:
        unique_together = ['user', 'exam', 'question']

Documentation about unique_together option: https://docs.djangoproject.com/fr/4.1/ref/models/options/#unique-together

  • Related