New to Django, do not judge strictly.

I want to make a simple site with a test. Two tables are needed for this: Question and Choices. Moreover, each question clearly corresponds to its 4 possible answers, only one of which is correct.

class Question(models.Model): question_text = models.CharField(max_length=300) # вариант ответа class Answer(models.Model): question = ForeginKey(Question, on_delete=models.CASCADE) # а вот здесь не знаю, как создать такой член класса, чтобы он # одновременно содержал 4 варианта ответа и удобно хранился в таблице 

Django version 2.1

  • Normal CharField . Answer option should contain one answer option. - Sergey Gornostaev
  • @SergeyGornostaev, so one CharField stores only one answer, and I need 4 options. Or why don't I understand? - Setplus
  • one
    Do not understand. Each instance of Answer should hold one answer. 4 answers are necessary - create four copies. - Sergey Gornostaev
  • This is detailed and at the same time simply described in the 2nd chapter of the Django manual . - Sergey Gornostaev
  • @SergeyGornostaev, I would like to implement this chapter, but to do the initialization not from the shell , but programmatically. - Setplus

1 answer 1

You can count one instance of the Answer class as one answer. You can create several answer choices and link each of them with a foreign key to an instance of the Question class.

 class Answer(models.Model): question = ForeginKey(Question, on_delete=models.CASCADE) answer_text = models.CharField(max_length=300) correct = models.BooleanField(default=False) # True, если ответ верный 
  • Thanks for the answer. Could you please explain how it is more intelligent to load these response options into the database table and count your answer for each object Answer ? - Setplus
  • "read for each object Answer your answer?" - Each Answer object is one answer and it can be correct or not. Each question will have several such objects attached to it. - Andrey
  • Do you have these answer options stored somewhere ready? - Andrey
  • in a text file if only. - Setplus
  • Create models, make migrations. Next, I would make a custom command as described here docs.djangoproject.com/en/2.1/howto/custom-management-commands . That is, run the command using manage.py load_answers , for example. And it will already read data from the file and create records in the database. - Andrey